#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <qdebug.h>
#include <qprocess.h>
#include <qdir.h>
#include <QThread>
#include <qfiledialog.h>
#include <qmessagebox.h>
#include <QFileDialog>
#include <QAxObject>
#include <QVariant>
#include <QList>
#include <qstandarditemmodel.h>
#include "showinfo.h"
#include "readfile.h"
// #include "usb_listenerh.h"
#include "usb_listener.h"
#include <QtSerialPort/QSerialPortInfo>
#include <QHeaderView>
#include <QStandardPaths>
#include <QDesktopServices>
#include <QDate>
#include <QTime>
#include "wthread.h"
#include "xlsxdocument.h"
#include "xlsxformat.h"
#define DEBUG 1

enum {
    IDLE,
    STATUS,
    WRITE,
    WIFI_CON,
    READ,
    BROADCOST,
    READBROADCOST,
    POLL,
    VERSION
};

enum {
    SEND_IDLE,
    SEND_DEAL,
    SEND_SUCCESS,
    SEND_FAIL
};

enum {
    OK,
    EMPTY,
    INFORMAT,
    INITERROR
};

enum {
    U_FREQ,
    V_FREQ
};

#define MAXSEC  30

static QString FREQ_LIST[] = {"401.02500", "136.02500"};

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    freq = U_FREQ;
    ui->setupUi(this);

    static const QDate buildDate = QLocale( QLocale::English ).toDate( QString(__DATE__).replace("  ", " 0"), "MMM dd yyyy");
    static const QTime buildTime = QTime::fromString(__TIME__, "hh:mm:ss");

    //ui->showlog->append(QString("BUILD DATA -> %1 %2").arg(buildDate.toString("yyyy.MM.dd")).arg(buildTime.toString()));

    //setWindowIcon(QIcon(":/res/icon.png"));

   // control_disenable();
   // ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
   // ui->tableWidget->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
   // ui->tableWidget->horizontalHeader()->setStretchLastSection(true);
   // ui->tableWidget->horizontalHeader()->setResizeContentsPrecision(QHeaderView::Stretch);

   //  QHeaderView* headerView = ui->tableWidget->horizontalHeader();
   //  headerView->setSectionResizeMode(QHeaderView::Stretch);
   // ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
   // table->horizontalHeader()->setStretchLastSection(true); //就是这个地方
//    ui->tableWidget->verticalHeader()->hide();
//    ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive);
//    ui->tableWidget->horizontalHeader()->setStretchLastSection(true);  // 最后一列伸缩铺满
//    ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
//    ui->tableWidget->setSelectionMode(QAbstractItemView::SingleSelection);
//    ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);

    rfile = new Readfile(devices);

    //d_ch = new ADD_D_CH();
    //a_ch = new ADD_A_CH();

    //connect(d_ch,SIGNAL(send_str(QString)),this,SLOT(deal_add_d_ch(QString)));
    //connect(a_ch,SIGNAL(send_str(QString)),this,SLOT(deal_add_a_ch(QString)));


    connect(rfile,SIGNAL(sendId(int)),this,SLOT(recvId(int)));
    connect(rfile,SIGNAL(wclose()),this,SLOT(deal_wclose()));

    wTh = new wThread();
   connect(wTh,SIGNAL(export_ok()),this,SLOT(thread_dealOk()));
    connect(wTh,SIGNAL(export_failed1()),this,SLOT(thread_dealFailed1()));
    connect(wTh,SIGNAL(export_failed2()),this,SLOT(thread_dealFailed2()));
    connect(wTh,SIGNAL(import_ret(int,QMap<int,CHANNINFO>*)),this,SLOT(thread_dealimport(int,QMap<int,CHANNINFO>*)));

    pollTh = new pollThread();
    connect(pollTh,SIGNAL(wiatfor1s(int)),this,SLOT(deal_wiatfor1s(int)));
    connect(pollTh,SIGNAL(timeout()),this,SLOT(deal_timeout()));
    connect(pollTh,SIGNAL(pollfinish()),this,SLOT(deal_pollfinish()));

//    ui->tableWidget->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel);

//    ui->tableWidget->setContextMenuPolicy(Qt::CustomContextMenu);
//    RightClick = new QMenu(ui->tableWidget);                        //右键点击菜单
//    deleteAction = new QAction(QString("delete"),this);     //删除事件
//    RightClick->addAction(deleteAction);
//    connect(ui->tableWidget,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(RightClickSlot(QPoint)));
//    connect(RightClick,SIGNAL(triggered(QAction*)),this,SLOT(RightClickDelete(QAction*)));
    event_init();
    SelectRowID = -1;
    channelSelectRow = -1;
    channelName = "";

    m_usb_listener = Q_NULLPTR;

    export_write = false;

    ui->sfilename->setFocusPolicy(Qt::NoFocus);
    //ui->sendfile->setFocusPolicy(Qt::NoFocus);

    ui->dev_status->setFont(QFont( "Timers" , 15 ,  QFont::Bold) );
    //ui->send_status->setFont(QFont( "Timers" , 15 ,  QFont::Bold) );
    //ui->read_status->setFont(QFont( "Timers" , 15 ,  QFont::Bold) );
    //ui->import_status->setFont(QFont( "Timers" , 15 ,  QFont::Bold) );
    ui->status->setFont(QFont( "Timers" , 15 ,  QFont::Bold) );

    //ui->label_ip->setFont(QFont( "Timers" , 10 ,  QFont::Bold) );
    //ui->label_port->setFont(QFont( "Timers" , 10 ,  QFont::Bold) );
    //ui->wifistatus->setFont(QFont( "Timers" , 10 ,  QFont::Bold) );


    //ui->label_ip->setText(" Ipaddress ");
    //ui->label_port->setText(" Port      ");

    //ui->showlog->setFocusPolicy(Qt::NoFocus);

    QFont font ("Microsoft YaHei", 12, 50);
    //ui->showlog->setFont(font);


    //sdcard_filepath = "/sdcard/";
    dir_str = "./SendText";
    send_filename = "./SendText/sendfile.xls";
    language = "English";
    if (language == "Chinese") {
        //ui->showlog->append("[ 默认为中文显示 ...... ]");
        ui->language->setText("中文");
    }

    if (language == "English") {
        //ui->showlog->append("[ 默认为英文显示 ...... ]");
        ui->language->setText("English");
    }


    //ui->showlog->append("[ 系统初始化 ...... ]");
    adb_code = IDLE;
    //device_num = 0;
    dealed_num = 0;
    waitsec = 0;
    revdevID = "";
    //switch_flag = 0;

    //ui->send_status->setText("Ready to start!");
    //ui->read_status->setText("Ready to start!");
    //ui->import_status->setText("Ready to start!");
    ui->status->setText("[ Current State  :  Ready to start! ]");

    process = new QProcess(this);
    connect(process,SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(onSearchFinished(int,QProcess::ExitStatus)));


    //areacfg = new areaConfig(wTh);

    //file_init();
    //on_pushButton_clicked();
    //setWindowFlags(windowFlags()&~Qt::WindowMaximizeButtonHint);
    usb_listener_init();
    ment_init();
    table_init();
    config_init();
    //ui->tableWidget->setModel(myModel);
    updateFreqDisplay();
    wTh->recvPara(ui->tableWidget,ui->areatable,headers,areaheaders,&channels);

    //process->start("adb version");
}

void MainWindow::event_init()
{
    //区域表
    ui->areatable->setContextMenuPolicy(Qt::CustomContextMenu);
    areaRightClick = new QMenu(ui->areatable);                        //点击菜单
    selectAction = new QAction(QString("Delect"),this);     //删除事件
    areaRightClick->addAction(selectAction);

    connect(ui->areatable,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(areaRightClickSlot(QPoint)));
    //单击事件
    connect(ui->areatable,SIGNAL(clicked(const QModelIndex &)), this, SLOT(onTableClicked(const QModelIndex &)));
    //右击删除事件
    connect(areaRightClick,SIGNAL(triggered(QAction*)),this,SLOT(areaRightClickDelete(QAction*)));



    ui->tableWidget->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel);
    ui->tableWidget->setContextMenuPolicy(Qt::CustomContextMenu);
    RightClick = new QMenu(ui->tableWidget);                        //右键点击菜单
    deleteAction = new QAction(QString("delect"),this);     //删除事件
    RightClick->addAction(deleteAction);
    //信道表单击事件
    connect(ui->tableWidget,SIGNAL(clicked(const QModelIndex &)), this, SLOT(channelonTableClicked(const QModelIndex &)));

    connect(ui->tableWidget,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(RightClickSlot(QPoint)));
    //信道表右击删除事件
    connect(RightClick,SIGNAL(triggered(QAction*)),this,SLOT(RightClickDelete(QAction*)));
}


//删除区域表的函数
void MainWindow::areaRightClickDelete(QAction *act)
{
    if (language == "English") {
        QMessageBox message(QMessageBox::NoIcon, QString("prompt"),
                                    QString("Do you choose the bank data?"),
        QMessageBox::Yes | QMessageBox::No, NULL);

        if (message.exec() != QMessageBox::Yes)
            return;
    }

    if (language == "Chinese") {
        QMessageBox message(QMessageBox::NoIcon, QString("提示"),
                                    QString("确定删除本行数据？"),
        QMessageBox::Yes | QMessageBox::No, NULL);

        if (message.exec() != QMessageBox::Yes)
            return;
    }


    //if(message.exec() == QMessageBox::Yes)
    {
        if(act->text() == QString("Delect"))   //看选中了删除这个菜单
        {
            QString str = QString("删除区域表 %1 行").arg(iselectcRow + 1);
            //ui->showlog->append(str);

            int trow = ui->areatable->rowCount();
            //qDebug() <<"22222" <<trow;
            //如果只有一行区域表，就不处理了
            if (trow == 1) {
                ui->areatable->clear();
                ui->areatable->setColumnCount(0);
                ui->areatable->setRowCount(0);
                ui->tableWidget->clear();
                ui->tableWidget->setColumnCount(0);
                ui->tableWidget->setRowCount(0);
                table_init();

                channelsTemp.clear();
                channels.clear();

                SelectRowID = -1;
                return;
            }

            //删除所选区域ID对应的所有信道数据
            QMap<int,CHANNINFO>::iterator  i;
            for(i = channels.begin(); i != channels.end();) {
                QStringList tmp = i.value().AreaID.split("#");
                QString aid = tmp.at(0);
                if (aid.toInt() == (iselectcRow + 1)) {
                    //qDebug() <<"删除ID" <<aid.toInt();
                    i = channels.erase(i);
                }
                else {
                    i++;
                }
            }

            //把数据更新到临时显示中,并把信道ID递减，从删除行之后
            channelsTemp.clear();
            for(i = channels.begin(); i != channels.end();) {
                QStringList tmp = i.value().AreaID.split("#");
                QString aid = tmp.at(0);
                //qDebug() << "---" <<aid.toInt() << "---" <<iselectcRow + 1;
                if (aid.toInt() > (iselectcRow + 1)) {
                    int a = aid.toInt() - 1;
                    QString str = QString("%1#%2#").arg(a).arg(tmp.at(1));
                    i.value().AreaID = str;
                    //channelsTemp.insert(channelsTemp.keys().size(),i.value());
                }
                channelsTemp.insert(channelsTemp.keys().size(),i.value());
                i++;
            }

            //拷贝
            channels.clear();
            channels = channelsTemp;


            //qDebug() << "iselectcRow = "<<iselectcRow;
            ui->areatable->removeRow(iselectcRow);  //删除掉了表格信息

            //更新删除行之后的区域ID
            update_areatable();

            //qDebug() << "删除后";
//            for(i = channels.begin(); i != channels.end();++i) {
//                //qDebug() <<i.key() <<"---" <<i.value().AreaID;
//            }

            ui->tableWidget->clear();
            ui->tableWidget->setColumnCount(0);
            ui->tableWidget->setRowCount(0);
            table_init();

            if (ui->areatable->rowCount() == 0)
                SelectRowID = -1;

        }
    }

    int row = ui->areatable->rowCount();
    qDebug() << "myy  iselectcRow = " <<iselectcRow;
    //iselectcRow
    //最后一行
    if ((iselectcRow == row) && (row != 0)) {
        QModelIndex index = ui->areatable->model()->index(iselectcRow-1,0);
        qDebug() << "1111111" <<iselectcRow << row;
        onTableClicked(index);
    }
    else if (iselectcRow != -1) {
        QModelIndex index = ui->areatable->model()->index(iselectcRow,0);
        onTableClicked(index);
    }
}

void MainWindow::update_areatable()
{
    //qDebug() << "删除的是第几行" << iselectcRow;

    int col = ui->areatable->columnCount();
    //总共多少行
    int rowcount = ui->areatable->rowCount();
    //qDebug() << "rowcount = " << rowcount;


    for (int i = iselectcRow; i < rowcount; i++) {
        int id;
        if (i == 0) {
            id = 1;
        }
        else {
            id = ui->areatable->item(i-1,0)->text().toInt();
            id += 1;
        }

        QString value = QString("%1").arg(id);
        QTableWidgetItem *item = new QTableWidgetItem(value);
        ui->areatable->setItem(i, 0, item);
        item->setFlags(item->flags() & (~Qt::ItemIsEditable));

        QString str = ui->areatable->item(i,1)->text();//取出字符串
        if (str.contains("Area",Qt::CaseSensitive)) {
            value = QString("Area%1").arg(id);
            QTableWidgetItem *item = new QTableWidgetItem(value);
            ui->areatable->setItem(i, 1, item);
        }
    }
}

void MainWindow::areaRightClickSlot(QPoint pos)
{
    QModelIndex index = ui->areatable->indexAt(pos);    //找到tableview当前位置信息
    iselectcRow = index.row();    //获取到了当前右键所选的行数
    if(index.isValid())        //如果行数有效，则显示菜单
    {
        areaRightClick->exec(QCursor::pos());
    }

}

//void MainWindow::RightClickDeletechannel(QAction *act)
//{
//    QMessageBox message(QMessageBox::NoIcon, QString("prompt"),
//                                QString("Do you choose the bank data?"),
//    QMessageBox::Yes | QMessageBox::No, NULL);

//    if(message.exec() == QMessageBox::Yes)
//    {
//        if(act->text() == QString("Delect"))   //看选中了删除这个菜单
//        {
//            int aid = ui->areatable->item(selectRowchannel,1)->text().toInt();
//            int cid = ui->channeltable->item(selectRowchannel,0)->text().toInt();
//            //update_channel(aid,cid);
//            ui->channeltable->removeRow(selectRowchannel);  //删除掉了表格信息

//            update_table(selectRowchannel);
//            Updatechannels(aid);

//        }
//    }
//}

//信道表的单击事件
void MainWindow::channelonTableClicked(const QModelIndex &index)
{
    qDebug() << "信道表的单击事件";

    int preSelectRowID = channelSelectRow;
    channelSelectRow = index.row();
    qDebug() << "上一次选择的行" << preSelectRowID << "本次选择嘚行" << channelSelectRow;


    //if (preSelectRowID == -1) {
    //    channelName = ui->tableWidget->item(index.row(),2)->text();
    //    return;
    // }

    //qDebug() << ui->tableWidget->item(preSelectRowID,2)->text();
    //qDebug() << channelName << channelName.size();

#if 0
    if (ui->tableWidget->item(preSelectRowID,2)->text().size() >= 18) {
        QString str = QString("The length of the [%1] is greater than 18").arg(ui->tableWidget->item(preSelectRowID,2)->text());
        QMessageBox::warning(NULL, "prompt", str, "OK");

        QTableWidgetItem *item = new QTableWidgetItem(channelName);
        ui->tableWidget->setItem(preSelectRowID, 2, item);
        //channelName =
    }
#endif
    channelName = ui->tableWidget->item(index.row(),2)->text();

//    qDebug() << "channelName = " <<channelName;
    qDebug() << ui->tableWidget->item(index.row(),7)->text()
             << ui->tableWidget->item(index.row(),8)->text()
             << ui->tableWidget->item(index.row(),9)->text()
             << ui->tableWidget->item(index.row(),10)->text()
             << ui->tableWidget->item(index.row(),11)->text();

    //提取上一次选择行的Name

    //SelectRowID = ui->tableWidget->item(index.row(),0);

    //在单击事件中弹出可以数据的界面
    //1、首先获取当前表格的数据
    QString No = ui->tableWidget->item(channelSelectRow,0)->text();
    QString AreaNo = ui->tableWidget->item(channelSelectRow,1)->text();
    QString ChannelName,ChannelType,TXFrequency,RXFrequency,ColorCode,Power,ChannelMode,CallType,
            Output,Input,Volume,Gain,Id,Num,List,Key,Encrypt;

    qDebug() << "No = " << No << "AreaNo" << AreaNo;

    QMap<int,CHANNINFO>::iterator i;
    for(i = channels.begin(); i != channels.end(); ++i) {

        qDebug()<<i.value().AreaID << " " << i.value().ChannelName << " " << i.value().ChannelType
               << " " <<i.value().TXFrequency << " " << i.value().RXFrequency << " "
               << i.value().ColorCode << " " << i.value().Power << " " << i.value().ChannelMode
               << " " << i.value().CallType << " " << i.value().OutputTimeslot
               << " " << i.value().InputTimeslot << " " << i.value().Volume << " "
               << i.value().MicGain << " " << i.value().Id;
        QString tAreaNo = i.value().AreaID.split("#").at(0);
        QString tNo = i.value().AreaID.split("#").at(1);
        qDebug() << "tNo = " << No << "AreaNo" << AreaNo;
        if ((tAreaNo == AreaNo) && (tNo == No)) {
            qDebug() << "匹配到了";
            //qDebug() << i.value().ChannelName;
             ChannelName = i.value().ChannelName;
             //qDebug() << i.value().ChannelType;
             ChannelType = i.value().ChannelType;
             //qDebug() << i.value().TXFrequency;
             TXFrequency = i.value().TXFrequency;
            // qDebug() << i.value().RXFrequency;
             RXFrequency = i.value().RXFrequency;
             //qDebug() << i.value().ColorCode;
             ColorCode = i.value().ColorCode;
             //qDebug() << i.value().Power;
             Power = i.value().Power;
             //qDebug() << i.value().ChannelMode;
             ChannelMode = i.value().ChannelMode;
             //qDebug() << i.value().CallType;
             CallType = i.value().CallType;
             //qDebug() << i.value().OutputTimeslot;
             Output = i.value().OutputTimeslot;
             //qDebug() << i.value().InputTimeslot;
             Input = i.value().InputTimeslot;
             //qDebug() << i.value().Volume;
             Volume = i.value().Volume;
             //qDebug() << i.value().MicGain;
             Gain = i.value().MicGain;
             //qDebug() << i.value().Id;
             Id = i.value().Id;
             Num = i.value().num;
             List = i.value().list;
             Key = i.value().key;
             Encrypt = i.value().encrypt;
             break;
        }
    }
    //return;
    //如果是模拟信道，要对亚音码进行处理，因为拿到的亚音码是数值，需要把它转换为对应的ID
//    if (ChannelType == "A")
//    {
//        qDebug() << "myy" << "接收亚音码" << ChannelMode << CallType << "发射亚音码" <<Output << Input;
//        //传入接收亚音类型和接收亚音码，得到接收亚音码对应的索引
//        if (ChannelMode != "1")
//            CallType = value_to_index(ChannelMode,CallType);

//        if (Output != "1")
//            Input = value_to_index(Output,Input);

//           qDebug() << "value_to_index" << ChannelMode << CallType << Output << Input;

//        if ((CallType == "Error") || (Input == "Error"))
//            return;
//    }


    QString str = ChannelName + "#" + RXFrequency + "#" + TXFrequency + "#" + Id + "#" +
            Power + "#" + ColorCode + "#" + ChannelMode + "#" + CallType + "#" +
            Output + "#" + Input + "#" + Volume + "#" + Gain + "#" + ChannelType + "#" +
            No + "#" + AreaNo + "#" + Num + "#" + List + "#" + Key + "#" + Encrypt + "#";

    qDebug() <<"要修改的数据" << str;

    moddata *md = new moddata(language,str);

    connect(md,SIGNAL(send_str(QString)),this,SLOT(deal_moddate(QString)));
    md->exec();
}

//根据索引得到数据
QString MainWindow::index_to_value(QString type,QString index)
{
    //"CTCSS" "5"
    QString filename;
    if (type == "2") //如果是CTCSS,解析 cparallel table
    {
        filename = "./ShowInfo/cparallel.txt";
    }
    else if ((type == "3") || (type == "4")) //如果是CDCSS,解析CDCSS
    {
        filename = "./ShowInfo/cdcss.txt";
    }
    else
        return "Error";

    QFile file(filename);
    if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        if (language == "English") {
            QString str = QString("open file[%1]feiled!").arg(filename);
            QMessageBox::warning(NULL, "prompt", str, "OK");
        }
        if (language == "Chinese") {
            QString str = QString("打开文件[%1]失败!").arg(filename);
            QMessageBox::warning(NULL, "提示", str, "确定");
        }
        return "Error";
    }
    while(!file.atEnd())
    {
        QByteArray line = file.readLine();
        QString str = QString(line);
        QStringList tmplist = str.split("#");
        QString tindex = QString("%1").arg(tmplist.at(0));
        tindex = tindex.simplified();
        tindex.replace(" ", "");

        if (tindex == index) {
            QString value = QString("%1").arg(tmplist.at(1));
            value = value.simplified();
            value.replace(" ", "");
            qDebug() << "找到对应的数据为" << value;
            file.close();
            return value;
        }
    }

    file.close();
    return "Error";
}

QString MainWindow::value_to_index(QString type,QString value)
{
    QString filename;
    if (type == "2") //如果是CTCSS,解析 cparallel table
    {
        filename = "./ShowInfo/cparallel.txt";
        qDebug() << "myy 解析cparallel.txt";
    }
    else if ((type == "3") || (type == "4")) //如果是CDCSS,解析CDCSS
    {
        filename = "./ShowInfo/cdcss.txt";
    }
    else
        return "Error";

    QFile file(filename);
    if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        if (language == "English") {
            QString str = QString("open file[%1]feiled!").arg(filename);
            QMessageBox::warning(NULL, "prompt", str, "OK");
        }
        if (language == "Chinese") {
            QString str = QString("打开文件[%1]失败!").arg(filename);
            QMessageBox::warning(NULL, "提示", str, "确定");
        }
        return "Error";
    }
    while(!file.atEnd())
    {
        QByteArray line = file.readLine();
        QString str = QString(line);
        QStringList tmplist = str.split("#");
        QString tvalue = QString("%1").arg(tmplist.at(1));
        tvalue = tvalue.simplified();
        tvalue.replace(" ", "");

        if (tvalue == value) {
            qDebug() << "找到对应的索引为" << QString("%1").arg(tmplist.at(0));
            file.close();
            return QString("%1").arg(tmplist.at(0));
        }
    }

    file.close();
    return "Error";
}

//区域表的单击事件
void MainWindow::onTableClicked(const QModelIndex &index)
{
    int preSelectRowID = SelectRowID;
    SelectRowID = ui->areatable->item(index.row(),0)->text().toInt();
    QString str = QString("当前选择区域表 %1 行").arg(SelectRowID);
    //ui->showlog->append(str);
    qDebug() << "SelectRowID = " <<SelectRowID << str;

    if (channels.keys().size() == 0) {
        //ui->showlog->append("退出");
        return;
    }

   //ui->showlog->append("继续往下执行");

    if (preSelectRowID != -1 && (preSelectRowID != SelectRowID) && ui->tableWidget->rowCount() != 0) {
        str = QString("上一次的选择 %1 行").arg(preSelectRowID);
        //ui->showlog->append(str);

        QMap<int,CHANNINFO>::iterator i;

       // qDebug() << channels.keys().size();
        //1、删除上一次修改的信道表的数据
        if (channels.keys().size() != 0) {
            for(i = channels.begin(); i != channels.end();) {
                QStringList tmp = i.value().AreaID.split("#");
                QString aid = tmp.at(0);
                if (aid.toInt() == preSelectRowID) {
                    i = channels.erase(i);
                    //qDebug() << "删除";
                }
                else {
                    i++;
                }
            }
        }

       qDebug() <<"删除完之后还剩多少个" <<channels.keys().size();


        //2、把数据拷贝到临时的缓存里
        channelsTemp.clear();
        if (channels.keys().size() != 0) {
            for(i = channels.begin(); i != channels.end();) {
                channelsTemp.insert(channelsTemp.keys().size(),i.value());
                i++;
            }
        }

        //3、把修改后的表格的数据添加到临时缓存
        int row = ui->tableWidget->rowCount();
        //qDebug() << "row = " <<row;
        for (int i = 0; i < row; i++) {
            CHANNINFO chaninfo;
            chaninfo.AreaID = QString("%1#%2#").arg(ui->tableWidget->item(i,1)->text()).
                    arg(ui->tableWidget->item(i,0)->text());
             chaninfo.ChannelName = ui->tableWidget->item(i,2)->text();
             chaninfo.ChannelType = ui->tableWidget->item(i,3)->text();
             chaninfo.TXFrequency = ui->tableWidget->item(i,4)->text();
             chaninfo.RXFrequency = ui->tableWidget->item(i,5)->text();
             chaninfo.ColorCode = ui->tableWidget->item(i,6)->text();
             chaninfo.Power = ui->tableWidget->item(i,7)->text();
             chaninfo.ChannelMode = ui->tableWidget->item(i,8)->text();
             chaninfo.CallType = ui->tableWidget->item(i,9)->text();
             chaninfo.OutputTimeslot = ui->tableWidget->item(i,10)->text();
             chaninfo.InputTimeslot = ui->tableWidget->item(i,11)->text();
             chaninfo.Volume = ui->tableWidget->item(i,12)->text();
             chaninfo.MicGain = ui->tableWidget->item(i,13)->text();
             chaninfo.Id = ui->tableWidget->item(i,14)->text();
             chaninfo.num = ui->tableWidget->item(i,15)->text();
             chaninfo.list = ui->tableWidget->item(i,16)->text();
             chaninfo.key = ui->tableWidget->item(i,17)->text();
             chaninfo.encrypt = ui->tableWidget->item(i,18)->text();
            channelsTemp.insert(channelsTemp.keys().size(),chaninfo);
        }

       qDebug() << "重新添加之后的大小"<<channelsTemp.keys().size();

        //4、把临时缓存的数据拷贝到显示缓存里
        channels.clear();
        channels = channelsTemp;


    }

    qDebug() << "保存上一次的修改之后" << channels.keys().size();

    QMap<int,CHANNINFO>::iterator i;
    for(i = channels.begin(); i != channels.end(); ++i) {
        qDebug() << i.value().AreaID;
    }

    ui->tableWidget->clear();
    ui->tableWidget->setColumnCount(0);
    ui->tableWidget->setRowCount(0);
    table_init();

    //QMap<int,CHANNINFO>::iterator i;

    int row = 0;

    for(i = channels.begin(); i != channels.end(); ++i) {

        int rowx = ui->tableWidget->rowCount();

        QStringList tmp = i.value().AreaID.split("#");
        QString aid = tmp.at(0);

        //qDebug() << aid << SelectRowID <<"-----------------";

        if (aid.toInt() != SelectRowID)
            continue;
        //qDebug() << "No" << tmp.at(1) << "AreaNo" <<tmp.at(0);
        QString str = QString("%1#").arg(rowx+1) + tmp.at(0) + "#"
                + i.value().ChannelName + "#" + i.value().ChannelType + "#"
                + i.value().TXFrequency + "#" + i.value().RXFrequency + "#"
                + i.value().ColorCode + "#" + i.value().Power + "#"
                + i.value().ChannelMode + "#" + i.value().CallType + "#"
                + i.value().OutputTimeslot + "#" + i.value().InputTimeslot + "#"
                + i.value().Volume + "#" + i.value().MicGain + "#" + i.value().Id + "#"
                + i.value().num + "#" + i.value().list + "#" + i.value().key + "#"
                + i.value().encrypt + "#";

        qDebug() << "找出区域表匹配的数据为" <<str;
        QStringList list = str.split("#");

        ui->tableWidget->insertRow(row);

        for (int j = 0; j < list.count()-1; j++) {
            //qDebug() <<"list.at(j)" <<list.at(j);
            QTableWidgetItem *item = new QTableWidgetItem(list.at(j));
            if (j == 0 || j == 1)
                item->setFlags(item->flags() & (~Qt::ItemIsEditable));
            ui->tableWidget->setItem(row, j, item);
        }
        row++;
    }

}

void MainWindow::config_init()
{
    //ui->showlog->append("配置初始化 ...");
    pull_path = "";
    push_path = "";
    broadcast = "";
    //flagfile_path = "";

    QFile file("./config.ini");
    if (file.exists())
    {
        //ui->showlog->append("配置文件存在.");
        //qDebug()<<"文件存在";
        //QMessageBox::warning(NULL, "prompt", "Config file is not exist", "OK");
        //QMessageBox::about(NULL, "About", "Config file is exist");
    }else {
        qDebug()<<"文件不存在";
        if(language == "English")
            QMessageBox::about(NULL, "About", "Config file is not exist,Must enter relevant information");
        if (language == "Chinese")
            QMessageBox::about(NULL, "提示", "配置文件不存在，请确保文件存在!");
        //this->close();
        exit(0);
    }

    m_IniFile = new QSettings("./config.ini", QSettings::IniFormat);


     pull_path = m_IniFile->value("PATH/pull").toString();
     push_path = m_IniFile->value("PATH/push").toString();
     broadcast = m_IniFile->value("INSTRUCTION/broadcast").toString();
     //flagfile_path = m_IniFile->value("FLAG_FILE/pull").toString();
     readbroadcast = m_IniFile->value("INSTRUCTION/readbroadcast").toString();

//     QPalette palette= ui->showlog->palette();
//      palette.setColor(QPalette::Base, Qt::black);
//      palette.setColor(QPalette::Text, Qt::green);
//      ui->showlog->setPalette(palette);

     //ui->showlog->append("读取配置 ... ");
    QString str = QString("pull_path = %1").arg(pull_path);
    //ui->showlog->append(str);

    str = QString("push_path = %1").arg(push_path);
    //ui->showlog->append(str);

    str = QString("broadcast = %1").arg(broadcast);
    //ui->showlog->append(str);

    str = QString("readbroadcast = %1").arg(readbroadcast);
    //ui->showlog->append(str);
    //ui->showlog->append("Done");


    ui->progressBar->setMinimum(0);
    ui->progressBar->setMaximum(MAXSEC);
    ui->progressBar->setValue(0);

     //ui->showlog->append("文件初始化 ... ");
    //新建文件夹
    QDir *photo = new QDir;
    bool exist = photo->exists("./RecvFile");
    if(!exist)
    {
       photo->mkdir("./RecvFile");
       //ui->showlog->append("文件夹 RecvFile 创建成功");
    }
    //ui->showlog->append("文件夹 RecvFile 存在");


    exist = photo->exists("./SendText");
    if(!exist)
    {
       photo->mkdir("./SendText");
       //ui->showlog->append("文件夹 SendText 创建成功");
    }
    //ui->showlog->append("文件夹 SendText 存在");

    //ui->showlog->append(QString("发送文件 %1").arg(send_filename));
    //ui->showlog->append(QString("接收文件 %1").arg("./RecvFile/recv.xls"));

    QByteArray pbyte = qgetenv("path");
    //qDebug() <<"pbyte = " <<pbyte;
    QString sbyte = pbyte;
    //ui->showlog->append(QString("系统环境变量 %1").arg(sbyte));

    QDir temDir("./adbTools");
    QString absDir = temDir.absolutePath();
    //qDebug()<<"绝对路径" <<absDir;

    QString sstr = QString("%1;%2").arg(sbyte).arg(QDir::toNativeSeparators(absDir));
    qputenv("path",sstr.toLatin1());

    pbyte = qgetenv("path");
    sbyte = pbyte;
    //qDebug() <<"pbyte = " <<pbyte;
    //ui->showlog->append(QString("设置之后 %1").arg(sbyte));

    adb_code = VERSION;
    process->start("adb version");


//    QString qEnvironmentVariable(const char *varName, const QString &defaultValue)
//    QString qEnvironmentVariable(const char *varName)

}

void MainWindow::ment_init()
{
    menuBar = new QMenuBar(this); //1.创建菜单栏
//    menuBar->setGeometry(0,0,width(),30);   //设置大小

    fileMenu = new QMenu("File",this);   //2.创建菜单
    //3.创建行为(Action)
    QAction *fileExportAction = new QAction("Export Excel File",this);
    connect(fileExportAction,SIGNAL(triggered()),this,SLOT(exportFile()));

    QAction *fileImportAction = new QAction("Import Excel File",this);
    connect(fileImportAction,SIGNAL(triggered()),this,SLOT(importFile()));

    QAction *Discription = new QAction("Software Discription",this);
    connect(Discription,SIGNAL(triggered()),this,SLOT(softdesc()));


    //4.将行为添加到菜单
    fileMenu->addAction(fileExportAction);
    fileMenu->addAction(fileImportAction);
    //fileMenu->addAction(Discription);

    //configMenu = new QMenu("Config",this);

    //QAction *con = new QAction("Area Config",this);
    //connect(con,SIGNAL(triggered()),this,SLOT(areaconfig()));

    //configMenu->addAction(con);

    aboutMenu = new QMenu("About",this);   //2.创建菜单
    QAction *version = new QAction("version 2.0",this);
    aboutMenu->addAction(version);

    menuBar->addMenu(fileMenu);
    //menuBar->addMenu(configMenu);
    menuBar->addMenu(aboutMenu);
    menuBar->setGeometry(0,0,this->width(),30);
    //ui->showlog->append("菜单初始化 ... Done");

}

//poll线程等待一秒时间到达，需要再次发起poll
void MainWindow::deal_wiatfor1s(int sec)
{
    //qDebug() << "子线程延时3s到";
    QString str = QString("等待时间 %1s").arg(sec);
    //ui->showlog->append(str);

    ui->progressBar->setValue(sec);
    readpoll();
}

void MainWindow::deal_timeout()
{
    pollTh->terminate();
    if (language == "English")
        QMessageBox::warning(NULL, "prompt", "Read File Prepare TimeOut", "OK");
    if (language == "Chinese")
        QMessageBox::warning(NULL, "提示", "读取文件准备超时", "确定");

    ui->status->setText("[ Current State  :  Ready to start! ]");
    ui->progressBar->setValue(0);
    waitsec = 0;
}

//poll成功
void MainWindow::deal_pollfinish()
{
    QString recvfile = "./RecvFile/recv.xls";
    QString send_file = QString("adb -s %1 pull %2 %3").arg(revdevID).arg(pull_path).arg(recvfile);
    adb_code = READ;
    process->start(send_file);
    ui->status->setText("[ Current State  :  Reading... ]");
    ui->progressBar->setValue(0);
}

void MainWindow::areaconfig()
{
    //areacfg->exec();
    //qDebug() << "1111111";
}

void MainWindow::table_init()
 {
//    ui->tableWidget->clear();
//    ui->tableWidget->setColumnCount(0);
//    ui->tableWidget->setRowCount(0);

//    ui->areatable->clear();
//    ui->areatable->setColumnCount(0);
//    ui->areatable->setRowCount(0);

    QString str;
    if (language == "English")
        str = "No#AreaNo#Channel Name#Channel Type#TX Freq#RF Freq#Color Code/Bandwidth#Power#Channel Mode/RX CTCSS Type#Call Type/RX CTCSS Code#Output Timeslot/TX CTCSS Type#Input Timeslot/TX CTCSS Code#Volume#Mic Gain/Mute#Local ID#Contact Num#Group List#Encrypt Key#Encrypt";
    if (language == "Chinese")
        str = "序号#区域号#信号名称#信道类型#发射频率#接收频率#色码/带宽#功率#信道模式/接收亚音类型#呼叫类型/接收亚音码#输出时隙/发射亚音类型#输入时隙/发射亚音码#音量#增益/静噪#本地ID#联系人号码#组呼列表#密钥#加密";
    //QString str = "No#AreaNo#Channel Name#Channel Type#TX Frequency#RX Frequency";

    headers = str.split("#");
    qDebug() <<"@@@@@" <<headers.size();

    ui->tableWidget->setColumnCount(headers.size()); //设置列数
    ui->tableWidget->setHorizontalHeaderLabels(headers);

//    for (int x = 0; x < headers.size(); x++)
//        ui->tableWidget->horizontalHeader()->setSectionResizeMode(x,QHeaderView::ResizeToContents);


    ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);//平均分配列宽

    //隐藏这些栏
    ui->tableWidget->setColumnHidden(0,true);
    ui->tableWidget->setColumnHidden(1,true);
    for (int i = 6; i < ui->tableWidget->columnCount(); i++) {
        ui->tableWidget->setColumnHidden(i,true);
    }

    //设置区域表
    if (language == "English")
        str = "No#Zone Area#Channel List";
    if (language == "Chinese")
        str = "序号#区域名#信道数";
    areaheaders = str.split("#");

    ui->areatable->setColumnCount(areaheaders.size()); //设置列数
    ui->areatable->setHorizontalHeaderLabels(areaheaders);

    //for (int x = 0; x < areaheaders.size(); x++)
    //    ui->areatable->horizontalHeader()->setSectionResizeMode(x,QHeaderView::ResizeToContents);

    ui->areatable->setSelectionBehavior(QAbstractItemView::SelectRows); //设置选择行为，以行为单位
    ui->areatable->setSelectionMode(QAbstractItemView::SingleSelection); //设置选择模式，选择单行
    //ui->areatable->horizontalHeader()->setStretchLastSection(true);
    ui->areatable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);//平均分配列宽

    //隐藏第一列
    ui->areatable->setColumnHidden(0,true);
    //ui->showlog->append("显示初始化 ... Done");
 }

void MainWindow::softdesc()
{
    //检查文件是否存在
    if (!showinfofileexist()) {
        Showinfo *senf = new Showinfo();
         senf->exec();//模
    }
}

void MainWindow::importFile()
{
    if (on_choose_file_clicked() == 0)
        on_switch_file_clicked();
}

void MainWindow::exportFile_fileNmae(QString fileName)
{
    qDebug() << "要开始导出了，在更新数据之前"<<channels.keys().size();
//    QMap<int,CHANNINFO>::iterator item;
//            for(item = channels.begin(); item != channels.end(); ++item) {

//                QStringList tmp = item.value().AreaID.split("#");

//                QString str = tmp.at(1) + "#" + tmp.at(0) + "#"
//                        + item.value().ChannelName + "#" + item.value().ChannelType + "#"
//                        + item.value().TXFrequency + "#" + item.value().RXFrequency + "#"
//                        + item.value().ColorCode + "#" + item.value().Power + "#"
//                        + item.value().ChannelMode + "#" + item.value().CallType + "#"
//                        + item.value().OutputTimeslot + "#" + item.value().InputTimeslot + "#"
//                        + item.value().Volume + "#" + item.value().MicGain + "#";

//                qDebug() << "str = " <<str;
//            }


    //导出的时候，先把当前显示区的数据进行更新

    int row = ui->tableWidget->rowCount();
    //qDebug() <<"当前处于那个界面" <<row;

    if (row != 0) {
        int aid = ui->tableWidget->item(0,1)->text().toInt();//取出字符串
        //qDebug() << "aid  =" <<aid;

        //删除原来的数据
        QMap<int,CHANNINFO>::iterator i;
        for(i = channels.begin(); i != channels.end();) {
            QStringList tmp = i.value().AreaID.split("#");
            QString said = tmp.at(0);
            if (said.toInt() == aid) {
                i = channels.erase(i);
            }
            else
                i++;

        }

        qDebug() <<"删除之后" << channels.keys().size() << ui->tableWidget->columnCount();
        for (int i = 0; i < ui->tableWidget->columnCount(); i++)
            qDebug() << ui->tableWidget->item(0,i)->text();

        //2、把数据拷贝到临时的缓存里
        channelsTemp.clear();
        if (channels.keys().size() != 0) {
            for(i = channels.begin(); i != channels.end();) {
                channelsTemp.insert(channelsTemp.keys().size(),i.value());
                i++;
            }
        }

        //把界面的数据重新添加到缓存里
        for (int i = 0; i < row; i++) {
            CHANNINFO chaninfo;
            chaninfo.AreaID = QString("%1#%2#").arg(ui->tableWidget->item(i,1)->text()).
                    arg(ui->tableWidget->item(i,0)->text());
             chaninfo.ChannelName = ui->tableWidget->item(i,2)->text();
             chaninfo.ChannelType = ui->tableWidget->item(i,3)->text();
             chaninfo.TXFrequency = ui->tableWidget->item(i,4)->text();
             chaninfo.RXFrequency = ui->tableWidget->item(i,5)->text();
             chaninfo.ColorCode = ui->tableWidget->item(i,6)->text();
             chaninfo.Power = ui->tableWidget->item(i,7)->text();
             chaninfo.ChannelMode = ui->tableWidget->item(i,8)->text();
             chaninfo.CallType = ui->tableWidget->item(i,9)->text();
             chaninfo.OutputTimeslot = ui->tableWidget->item(i,10)->text();
             chaninfo.InputTimeslot = ui->tableWidget->item(i,11)->text();
             chaninfo.Volume = ui->tableWidget->item(i,12)->text();
             chaninfo.MicGain = ui->tableWidget->item(i,13)->text();
             chaninfo.Id = ui->tableWidget->item(i,14)->text();
             chaninfo.num = ui->tableWidget->item(i,15)->text();
             chaninfo.list = ui->tableWidget->item(i,16)->text();
             chaninfo.key = ui->tableWidget->item(i,17)->text();
             chaninfo.encrypt = ui->tableWidget->item(i,18)->text();

            channelsTemp.insert(channelsTemp.keys().size(),chaninfo);
        }

        qDebug() <<"添加之后" << channels.keys().size();
//                channelsTemp.clear();
//                for(i = channels.begin(); i != channels.end();) {
//                    channelsTemp.insert(channelsTemp.keys().size(),i.value());
//                     i++;
//                }

        channels.clear();
        channels = channelsTemp;

    }

//            qDebug() << "开始导出，数据为" <<channels.keys().size();
//            //QMap<int,CHANNINFO>::iterator item;
//            for(item = channels.begin(); item != channels.end(); ++item) {

//                QStringList tmp = item.value().AreaID.split("#");

//                QString str = tmp.at(1) + "#" + tmp.at(0) + "#"
//                        + item.value().ChannelName + "#" + item.value().ChannelType + "#"
//                        + item.value().TXFrequency + "#" + item.value().RXFrequency + "#"
//                        + item.value().ColorCode + "#" + item.value().Power + "#"
//                        + item.value().ChannelMode + "#" + item.value().CallType + "#"
//                        + item.value().OutputTimeslot + "#" + item.value().InputTimeslot + "#"
//                        + item.value().Volume + "#" + item.value().MicGain + "#";

//                qDebug() << "str = " <<str;
//            }


    //ui->showlog->append(QString("导出数据为 %1").arg(fileName));
    wTh->setExport();
    //wTh->recvPara(ui->tableWidget,fileName,headers);
    wTh->recvQmap(&channels);
    wTh->getExportfilepath(fileName);
    wTh->start();
}

void MainWindow::exportFile()
{
    //qDebug() <<"helloo";
    int col = ui->areatable->columnCount();
    int row = ui->areatable->rowCount();

    if (col == 0 || row == 0) {
        if (language == "English")
             QMessageBox::warning(NULL, "prompt", "There is no data!", "OK");

        if (language == "Chinese")
             QMessageBox::warning(NULL, "提示", "没有数据!", "确定");

        return;
    }

    if (channelSelectRow != -1) {
        QString str = ui->tableWidget->item(channelSelectRow,2)->text();
        //qDebug() << "导出的时候" << channelSelectRow << str;
        if (str.size() >= 18) {
            QString str1 = QString("The length of the [%1] is greater than 18").arg(str);
            QMessageBox::warning(NULL, "prompt", str1, "OK");
            return;
        }
    }


 //   QString fileName = QFileDialog::getSaveFileName(this, tr("Excel file"), qApp->applicationDirPath (),
     //                                               tr("Excel Files (*.xls)"));
 //   if (fileName.isEmpty())
//        return;


    //recv_filename
//    QString xsl_file = "./11111.xls";

//    QDir temDir(xsl_file);
//    QString absDir = temDir.absolutePath();


    //newExcel(absDir);
 //   Table2Excel(ui->tableWidget);

    ui->status->setText("[ Current State  :  Exporting... ]");

//    QString fileName = QFileDialog::getSaveFileName(this, tr("Save excel"),
//    ".", tr("Microsoft Office 2003 (*.xls)"));//获取保存路径
      QString fileName = QFileDialog::getSaveFileName(this, tr("Excel file"), qApp->applicationDirPath (),
                                                       tr("Excel Files (*.xls)"));
        if (fileName!="")
        {
            exportFile_fileNmae(fileName);
        } else {
            ui->status->setText("[ Current State  :  Ready to start! ]");
        }
}

void MainWindow::thread_dealOk()
{
    //该分支为write之前的导出
    if (export_write == true) {
        qDebug() << "导出成功，开始发送";
        //ui->showlog->append("导出成功，开始发送");
        export_write = false;
        dealed_num = 0;
        adb_code = WRITE;
        find_hash();

        ui->send->setEnabled(false);
    } else {
        if (language == "English")
            QMessageBox::information(this,"prompt","Export File Finish!");
        if (language == "Chinese")
            QMessageBox::information(this,"提示","文件导出结束!");

        ui->status->setText("[ Current State  :  Ready to start! ]");
        qDebug() << "导出结束之后还有多少数据" <<channels.keys().size();

        QMap<int,CHANNINFO>::iterator item;
        for(item = channels.begin(); item != channels.end(); ++item) {

            QStringList tmp = item.value().AreaID.split("#");

            QString str = tmp.at(1) + "#" + tmp.at(0) + "#"
                    + item.value().ChannelName + "#" + item.value().ChannelType + "#"
                    + item.value().TXFrequency + "#" + item.value().RXFrequency + "#"
                    + item.value().ColorCode + "#" + item.value().Power + "#"
                    + item.value().ChannelMode + "#" + item.value().CallType + "#"
                    + item.value().OutputTimeslot + "#" + item.value().InputTimeslot + "#"
                    + item.value().Volume + "#" + item.value().MicGain + "#";

            qDebug() << "str = " <<str;
        }
    }

}

void MainWindow::thread_dealFailed1()
{
    //QMessageBox::information(this,"ERR","Export File Finish!");
    if (language == "English")
        QMessageBox::warning(NULL,"ERR","Failed to create Excel object, please install Microsoft Excel",QMessageBox::Apply);

    if (language == "Chinese")
        QMessageBox::warning(NULL,"错误","创建文件失败, 请安装Microsoft Excel",QMessageBox::Apply);

    ui->status->setText("[ Current State  :  Ready to start! ]");
}

void MainWindow::thread_dealFailed2()
{
    ui->status->setText("[ Current State  :  Ready to start! ]");
}

void MainWindow::thread_dealimport(int ret,QMap<int,CHANNINFO> *map)
{
    qDebug() << "进入信号处理函数thread_dealimport" << (map)->keys().size();
    if (ret) {
        if (ret == EMPTY) {
            if (language == "English")
                 QMessageBox::warning(NULL, "prompt", "Import file is empty!", "OK");

            if (language == "Chinese")
                QMessageBox::warning(NULL, "提示", "导入文件为空!", "确定");
        }
        if (ret == INFORMAT) {
            if (language == "English")
                QMessageBox::warning(NULL, "prompt", "Import file is Invalid format!", "OK");
            if (language == "Chinese")
                QMessageBox::warning(NULL, "提示", "文件格式有误", "确定");
        }
        if (ret == INITERROR) {
            if (language == "English")
                QMessageBox::warning(NULL, "prompt", "INIT OleInitialize failed! ", "OK");
            if (language == "Chinese")
                QMessageBox::warning(NULL, "提示", "初始化失败", "确定");
        }

         ui->status->setText("[ Current State  :  Ready to start! ]");
    } else {
        ui->tableWidget->clear();
        ui->tableWidget->setColumnCount(0);
        ui->tableWidget->setRowCount(0);
        table_init();
        channels.clear();
        channels = *map;
        if (language == "English") {
            QString str = QString("Import file successful!");
            QMessageBox::warning(NULL, str, "OK");
        }
        if (language == "Chinese")
            QMessageBox::warning(NULL, "文件导入成功", "确定");
        channelSelectRow = -1;
        SelectRowID = -1;
        qDebug() << "导入成功，数据为" <<channels.keys().size();

        QMap<int,CHANNINFO>::iterator  i;
        for(i = channels.begin(); i != channels.end();) {
            if (i.value().ChannelType == "A") {
                if (i.value().ChannelMode != "1")
                    i.value().CallType = index_to_value(i.value().ChannelMode,i.value().CallType);
                if (i.value().OutputTimeslot != "1")
                    i.value().InputTimeslot = index_to_value(i.value().OutputTimeslot,i.value().InputTimeslot);
            }
            qDebug()<<i.value().AreaID << i.value().ChannelName<< i.value().ChannelType
                   <<i.value().TXFrequency<< i.value().RXFrequency <<i.value().ColorCode
                  << i.value().Power << i.value().ChannelMode<< i.value().CallType
                  << i.value().OutputTimeslot << i.value().InputTimeslot << i.value().Volume
                  <<i.value().MicGain << i.value().Id;
            i++;
        }

        ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows); //设置选择行为，以行为单位
        ui->tableWidget->setSelectionMode(QAbstractItemView::SingleSelection); //设置选择模式，选择单行
    }
    //ui->tableWidget->setEnabled(true);
    ui->switch_file->setEnabled(true);
    ui->status->setText("[ Current State  :  Ready to start! ]");

}

void MainWindow::Table2Excel(QTableWidget *table,QString title)
{
//    QString fileName = QFileDialog::getSaveFileName(table, "保存",
//                QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation),
//                "Excel 文件(*.xls *.xlsx)");
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save excel"),
    ".", tr("Microsoft Office 2003 (*.xls)"));//获取保存路径
        if (fileName!="")
        {
            QAxObject *excel = new QAxObject;
            if (excel->setControl("Excel.Application")) //连接Excel控件
            {
                excel->dynamicCall("SetVisible (bool Visible)","false");//不显示窗体
                excel->setProperty("DisplayAlerts", false);//不显示任何警告信息。如果为true那么在关闭是会出现类似“文件已修改，是否保存”的提示
                QAxObject *workbooks = excel->querySubObject("WorkBooks");//获取工作簿集合
                workbooks->dynamicCall("Add");//新建一个工作簿
                QAxObject *workbook = excel->querySubObject("ActiveWorkBook");//获取当前工作簿
                QAxObject *worksheet = workbook->querySubObject("Worksheets(int)", 1);
                int i,j,colcount=table->columnCount();
                QAxObject *cell,*col;
                //标题行
//                cell=worksheet->querySubObject("Cells(int,int)", 1, 1);
//                cell->dynamicCall("SetValue(const QString&)", title);
//                cell->querySubObject("Font")->setProperty("Size", 18);
                //调整行高
//                worksheet->querySubObject("Range(const QString&)", "1:1")->setProperty("RowHeight", 30);
                //合并标题行
                QString cellTitle;
//                cellTitle.append("A1:");
//                cellTitle.append(QChar(colcount - 1 + 'A'));
 //               cellTitle.append(QString::number(1));
 //              QAxObject *range = worksheet->querySubObject("Range(const QString&)", cellTitle);
 //               range->setProperty("WrapText", true);
 //               range->setProperty("MergeCells", true);
 //               range->setProperty("HorizontalAlignment", -4108);//xlCenter
  //              range->setProperty("VerticalAlignment", -4108);//xlCenter
                //列标题
                for(i=0;i<colcount;i++)
                {
                    QString columnName;
                    columnName.append(QChar(i  + 'A'));
                    columnName.append(":");
                    columnName.append(QChar(i + 'A'));
                    col = worksheet->querySubObject("Columns(const QString&)", columnName);
                    col->setProperty("ColumnWidth", table->columnWidth(i)/6);
                    cell=worksheet->querySubObject("Cells(int,int)", 1, i+1);
                    columnName=table->horizontalHeaderItem(i)->text();
                    cell->dynamicCall("SetValue(const QString&)", columnName);
                    cell->querySubObject("Font")->setProperty("Bold", true);
                    cell->querySubObject("Interior")->setProperty("Color",QColor(191, 191, 191));
                    cell->setProperty("HorizontalAlignment", -4108);//xlCenter
                    cell->setProperty("VerticalAlignment", -4108);//xlCenter
                }
                //数据区
                for(i=0;i<table->rowCount();i++){
                    for (j=0;j<colcount;j++)
                    {
                        worksheet->querySubObject("Cells(int,int)", i+2, j+1)->dynamicCall("SetValue(const QString&)", table->item(i,j)?table->item(i,j)->text():"");
                    }
                }
                //画框线
                QString lrange;
                lrange.append("A1:");
                lrange.append(colcount - 1 + 'A');
                lrange.append(QString::number(table->rowCount() + 2));
       //         range = worksheet->querySubObject("Range(const QString&)", lrange);
      //          range->querySubObject("Borders")->setProperty("LineStyle", QString::number(1));
      //          range->querySubObject("Borders")->setProperty("Color", QColor(0, 0, 0));
                //调整数据区行高
                QString rowsName;
                rowsName.append("1:");
                rowsName.append(QString::number(table->rowCount() + 1));
                //range = worksheet->querySubObject("Range(const QString&)", rowsName);
                //range->setProperty("RowHeight", 20);
                workbook->dynamicCall("SaveAs(const QString&)",QDir::toNativeSeparators(fileName));//保存至fileName
                workbook->dynamicCall("Close()");//关闭工作簿
                excel->dynamicCall("Quit()");//关闭excel
                delete excel;
                excel=NULL;
                if (QMessageBox::question(NULL,"finish","The file has been exported, open it now？",QMessageBox::Yes|QMessageBox::No)==QMessageBox::Yes)
                {
                    QDesktopServices::openUrl(QUrl("file:///" + QDir::toNativeSeparators(fileName)));
                }
            }
            else
            {
                QMessageBox::warning(NULL,"ERR","Failed to create Excel object, please install Microsoft Excel。",QMessageBox::Apply);
            }
        }

}



void MainWindow::writetoExcel(QTableWidget *table,QString fileName)
{
//    QString fileName = QFileDialog::getSaveFileName(table, "请选择文件保存路径",
//                QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation),
//                "Excel 文件(*.xls *.xlsx)");

    QDir temDir(fileName);
    QString absDir = temDir.absolutePath();

    if (absDir!="")
    {
        QAxObject *excel = new QAxObject;
        if (excel->setControl("Excel.Application")) //连接Excel控件
        {
            excel->dynamicCall("SetVisible (bool Visible)","false");//不显示窗体
            excel->setProperty("DisplayAlerts", false);//不显示任何警告信息。如果为true那么在关闭是会出现类似“文件已修改，是否保存”的提示
            QAxObject *workbooks = excel->querySubObject("WorkBooks");//获取工作簿集合
            workbooks->dynamicCall("Add");//新建一个工作簿
            QAxObject *workbook = excel->querySubObject("ActiveWorkBook");//获取当前工作簿
            QAxObject *worksheet = workbook->querySubObject("Worksheets(int)", 1);
            int i,j,colcount=table->columnCount();
            QAxObject *cell,*col;
           for(i=0;i<colcount;i++)
            {
                QString columnName;
                columnName.append(QChar(i  + 'A'));
                columnName.append(":");
                columnName.append(QChar(i + 'A'));
                col = worksheet->querySubObject("Columns(const QString&)", columnName);
                col->setProperty("ColumnWidth", table->columnWidth(i)/6);
                cell=worksheet->querySubObject("Cells(int,int)", 1, i+1);
                columnName=table->horizontalHeaderItem(i)->text();
                cell->dynamicCall("SetValue(const QString&)", columnName);
                cell->querySubObject("Font")->setProperty("Bold", true);
                cell->querySubObject("Interior")->setProperty("Color",QColor(191, 191, 191));
                cell->setProperty("HorizontalAlignment", -4108);//xlCenter
                cell->setProperty("VerticalAlignment", -4108);//xlCenter
            }
            //数据区
            for(i=0;i<table->rowCount();i++){
                for (j=0;j<colcount;j++)
                {
                    worksheet->querySubObject("Cells(int,int)", i+2, j+1)->dynamicCall("SetValue(const QString&)", table->item(i,j)?table->item(i,j)->text():"");
                }
            }
            //画框线
            QString lrange;
            lrange.append("A1:");
            lrange.append(colcount - 1 + 'A');
            lrange.append(QString::number(table->rowCount() + 2));
          //调整数据区行高
            QString rowsName;
            rowsName.append("1:");
            rowsName.append(QString::number(table->rowCount() + 1));
           workbook->dynamicCall("SaveAs(const QString&)",QDir::toNativeSeparators(absDir));//保存至fileName
            workbook->dynamicCall("Close()");//关闭工作簿
            excel->dynamicCall("Quit()");//关闭excel
            delete excel;
            excel=NULL;
        }
        else
        {
            QMessageBox::warning(NULL,"ERR","Failed to create Excel object, please install Microsoft Excel。",QMessageBox::Apply);
        }
    }

}


void MainWindow::exportSlot(QTableWidget *table)
{

    QString filepath=QFileDialog::getSaveFileName(table, "保存",
                                                  QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation),
                                                  "Excel 文件(*.xls *.xlsx)");
        if(!filepath.isEmpty()){
            QAxObject *excel = new QAxObject(this);
            excel->setControl("Excel.Application");//连接Excel控件
            excel->dynamicCall("SetVisible (bool Visible)","false");//不显示窗体
            excel->setProperty("DisplayAlerts", false);//不显示任何警告信息。如果为true那么在关闭是会出现类似“文件已修改，是否保存”的提示

            QAxObject *workbooks = excel->querySubObject("WorkBooks");//获取工作簿集合
            workbooks->dynamicCall("Add");//新建一个工作簿
            QAxObject *workbook = excel->querySubObject("ActiveWorkBook");//获取当前工作簿
            QAxObject *worksheets = workbook->querySubObject("Sheets");//获取工作表集合
            QAxObject *worksheet = worksheets->querySubObject("Item(int)",1);//获取工作表集合的工作表1，即sheet1
            QAxObject *cellX,*cellY;

//            int col = ui->tableWidget->columnCount();
 //           int row = ui->tableWidget->rowCount();


            int curRow = table->rowCount();
            int col = ui->tableWidget->columnCount();

            for(int i = 0; i < curRow; i++){
                QString index = "A";
                for (int j = 0; j < col; j++) {
                    QString X=index+j+QString::number(i+1);//设置要操作的单元格，如A1
                    //QString Y="B"+QString::number(i+1);
                    cellX = worksheet->querySubObject("Range(QVariant, QVariant)",X);//获取单元格
                    //cellY = worksheet->querySubObject("Range(QVariant, QVariant)",Y);

                    cellX->dynamicCall("SetValue(const QVariant&)",QVariant(table->item(i,j)->text()));//设置单元格的值
//                    cellY->dynamicCall("SetValue(const QVariant&)",QVariant(table->item(i,1)->text()));
                }
            }

            workbook->dynamicCall("SaveAs(const QString&)",QDir::toNativeSeparators(filepath));//保存至filepath，注意一定要用QDir::toNativeSeparators将路径中的"/"转换为"\"，不然一定保存不了。
            workbook->dynamicCall("Close()");//关闭工作簿
            excel->dynamicCall("Quit()");//关闭excel
            delete excel;
            excel=NULL;
        }
}

void MainWindow::newExcel(const QString &fileName)
{
    pApplication = new QAxObject();
    //连接Excel控件
    pApplication->setControl("Excel.Application");
    //false不显示窗体（看具体过程）
    pApplication->dynamicCall("SetVisible(bool)", false);
    //不显示任何警告信息
    pApplication->setProperty("DisplayAlerts", false);

    pWorkBooks = pApplication->querySubObject("Workbooks");

    QFile file(fileName);
    if (file.exists())
    {
        pWorkBook = pWorkBooks->querySubObject(
            "Open(const QString &", fileName);
    }else {
        pWorkBooks->dynamicCall("Add");
        pWorkBook =
            pApplication->querySubObject("ActiveWorkBook");
    }
    //默认有一个worksheet
    pSheets = pWorkBook->querySubObject("Sheets");
    pSheet = pSheets->querySubObject("Item(int)",1);
}

void MainWindow::setCellValue(int row, int column
    , const QString &value)
{
    QAxObject *pRange = pSheet->querySubObject("Cells(int,int)"
        , row, column);
    pRange->dynamicCall("Value", value);
    //内容居中
    pRange->setProperty("HorizontalAlignment", -4108);
    pRange->setProperty("VerticalAlignment", -4108);
}

void MainWindow::setCellValue(int row, int column
    , const int &value)
{
    QAxObject *pRange = pSheet->querySubObject("Cells(int,int)"
        , row, column);
    pRange->setProperty("Value", value);
    //内容居中
    pRange->setProperty("HorizontalAlignment", -4108);
    pRange->setProperty("VerticalAlignment", -4108);
}
void MainWindow::saveExcel(const QString &fileName)
{
    pWorkBook->dynamicCall("SaveAs(const QString &)",
        QDir::toNativeSeparators(fileName));

    pApplication->dynamicCall("Quit(void)");  //退出
    delete pApplication;
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::usb_listener_init()
{
    m_usb_listener = new usb_listener;
    qApp->installNativeEventFilter(m_usb_listener);
#if 0
       connect(m_usb_listener, &usb_listener::DevicePlugIn, [=](){
           qDebug("捕获到usb设备变动，调用状态检查函数...");
           //on_pushButton_clicked();
       });
       m_usb_listener->EmitMySignal();     //手动触发一次
#endif
       //ui->label->setText("hello world");
       //qDebug("hello");
     connect(m_usb_listener,SIGNAL(DevicePlugIn()),this,SLOT(usb_deal()));
     connect(m_usb_listener,SIGNAL(DevicePlugOut()),this,SLOT(usb_deal()));
     //m_usb_listener->EmitMySignal();     //手动触发一次
     //ui->showlog->append("USB 接口初始化 ... Done");
}

void MainWindow::usb_deal()
{
    qDebug("捕获到usb设备变动，调用状态检查函数...");
    on_pushButton_clicked();
}


void MainWindow::RightClickSlot(QPoint pos)
{
    QModelIndex index = ui->tableWidget->indexAt(pos);    //找到tableview当前位置信息
    selectRowchannel = index.row();    //获取到了当前右键所选的行数

    if(index.isValid())        //如果行数有效，则显示菜单
    {
        qDebug() << "RightClickSlot" << selectRowchannel;
        RightClick->exec(QCursor::pos());
    }
}


//删除信道的函数
void MainWindow::RightClickDelete(QAction *act)
{
    if (language == "Chinese") {
        QMessageBox message(QMessageBox::NoIcon, QString("提示"),
                                    QString("选择本行数据?"),
        QMessageBox::Yes | QMessageBox::No, NULL);

        if(message.exec() == QMessageBox::Yes)
        {

            //ui->showlog->append(QString("删除信道表信息 %1").arg(selectRowchannel));
            if(act->text() == QString("delect"))   //看选中了删除这个菜单
            {

                int aid = ui->tableWidget->item(selectRowchannel,1)->text().toInt();
                int cid = ui->tableWidget->item(selectRowchannel,0)->text().toInt();
                //update_channel(aid,cid);
                //qDebug() << "RightClickDelete" << selectRowchannel;
                ui->tableWidget->removeRow(selectRowchannel);  //删除掉了表格信息

                //更新信道表数据
                update_table(selectRowchannel);

                //更新所属区域个数
                Updatechannels(aid);

            }
        }

    }


    if (language == "English") {
        QMessageBox message(QMessageBox::NoIcon, QString("prompt"),
                                    QString("Do you choose the bank data?"),
        QMessageBox::Yes | QMessageBox::No, NULL);

        if(message.exec() == QMessageBox::Yes)
        {

            //ui->showlog->append(QString("删除信道表信息 %1").arg(selectRowchannel));
            if(act->text() == QString("delect"))   //看选中了删除这个菜单
            {

                int aid = ui->tableWidget->item(selectRowchannel,1)->text().toInt();
                int cid = ui->tableWidget->item(selectRowchannel,0)->text().toInt();
                //update_channel(aid,cid);
                //qDebug() << "RightClickDelete" << selectRowchannel;
                ui->tableWidget->removeRow(selectRowchannel);  //删除掉了表格信息

                //更新信道表数据
                update_table(selectRowchannel);

                //更新所属区域个数
                Updatechannels(aid);

            }
        }
    }

//    //弹出提示框，看是否数据
//    QMessageBox message(QMessageBox::NoIcon, QString("prompt"),
//                                QString("Whether to delete the bank data?"),
//    QMessageBox::Yes | QMessageBox::No, NULL);

//    //如确认删除
//    if(message.exec() == QMessageBox::Yes)
//    {
//        if(act->text() == QString("delete"))   //看选中了删除这个菜单
//        {
//            ui->tableWidget->removeRow(iDeletcRow);  //删除掉了表格信息
//            update_table(iDeletcRow);
//        }
//    }
}

void MainWindow::update_table(int row)
{
    //ui->showlog->append(QString("删除的是第几行 %1").arg(row));

    int col = ui->tableWidget->columnCount();
    //总共多少行
    int rowcount = ui->tableWidget->rowCount();
    //ui->showlog->append(QString("总共多少行 %1").arg(rowcount));
    //qDebug() << "rowcount = " << rowcount;

    //ui->showlog->append("更新表格");

    //更新表格
    for (int i = row; i < rowcount; i++) {
        int id;
        if (i == 0) {
            id = 1;
        }
        else {
            //找到前面的一行，也就是没有修改的一行
            id = ui->tableWidget->item(i-1,0)->text().toInt();
            id += 1;
        }

        //更新id
        QString value = QString("%1").arg(id);
        QTableWidgetItem *item = new QTableWidgetItem(value);
        ui->tableWidget->setItem(i, 0, item);

        //取出name字符串
//        QString str = ui->tableWidget->item(i,2)->text();
//        if (str.contains("Channel",Qt::CaseSensitive)) {
//            QString s = "Channel";
//            int index = str.indexOf(s);
//            value = str.left(index) + QString("Channel%1").arg(id);

//            //value = QString("Channel%1").arg(id);
//            QTableWidgetItem *item = new QTableWidgetItem(value);
//            ui->tableWidget->setItem(i, 2, item);
//        }

    }

     col = ui->tableWidget->columnCount();
    //总共多少行
     rowcount = ui->tableWidget->rowCount();
     //ui->showlog->append(QString("更新表格之后 %1 行").arg(rowcount));

     //更新MAP
     QMap<int,CHANNINFO>::iterator  i;
     for(i = channels.begin(); i != channels.end();) {
         QStringList tmp = i.value().AreaID.split("#");
         QString aid = tmp.at(0);
         //qDebug()<<"aid.toInt()"<<aid.toInt()<< " == " <<"SelectRowID"<<SelectRowID;
         if (aid.toInt() == (SelectRowID)) {
             i = channels.erase(i);
         }
         else {
             i++;
         }
     }

     channelsTemp.clear();

     for(i = channels.begin(); i != channels.end();) {
         channelsTemp.insert(channelsTemp.keys().size(),i.value());
         i++;
     }

     for (int i = 0; i < rowcount; i++) {
            CHANNINFO chaninfo;
            chaninfo.AreaID = QString("%1#%2#").arg(ui->tableWidget->item(i,1)->text()).
                    arg(ui->tableWidget->item(i,0)->text());
             chaninfo.ChannelName = ui->tableWidget->item(i,2)->text();
             chaninfo.ChannelType = ui->tableWidget->item(i,3)->text();
             chaninfo.TXFrequency = ui->tableWidget->item(i,4)->text();
             chaninfo.RXFrequency = ui->tableWidget->item(i,5)->text();
             chaninfo.ColorCode = ui->tableWidget->item(i,6)->text();
             chaninfo.Power = ui->tableWidget->item(i,7)->text();
             chaninfo.ChannelMode = ui->tableWidget->item(i,8)->text();
             chaninfo.CallType = ui->tableWidget->item(i,9)->text();
             chaninfo.OutputTimeslot = ui->tableWidget->item(i,10)->text();
             chaninfo.InputTimeslot = ui->tableWidget->item(i,11)->text();
             chaninfo.Volume = ui->tableWidget->item(i,12)->text();
             chaninfo.MicGain = ui->tableWidget->item(i,13)->text();             
             chaninfo.num = ui->tableWidget->item(i,15)->text();
             chaninfo.list = ui->tableWidget->item(i,16)->text();
             chaninfo.key = ui->tableWidget->item(i,17)->text();
             chaninfo.encrypt = ui->tableWidget->item(i,18)->text();
            channelsTemp.insert(channelsTemp.keys().size(),chaninfo);
     }


    channels.clear();
    channels = channelsTemp;
    Updatechannels(SelectRowID);
}

//void MainWindow::update_table(int row)
//{
//    qDebug() << "删除的是第几行" << row;

//    int col = ui->tableWidget->columnCount();
//    //总共多少行
//    int rowcount = ui->tableWidget->rowCount();
//    qDebug() << "rowcount = " << rowcount;


//    for (int i = row; i < rowcount; i++) {
//        int id;
//        if (i == 0) {
//            id = 1;
//        }
//        else {
//            id = ui->tableWidget->item(i-1,0)->text().toInt();
//            id += 1;
//        }
//        QString value = QString("%1").arg(id);
//        QTableWidgetItem *item = new QTableWidgetItem(value);
//        ui->tableWidget->setItem(i, 0, item);

//        QString str = ui->tableWidget->item(i,1)->text();//取出字符串
//        if (str.contains("Channel",Qt::CaseSensitive)) {
//            value = QString("Channel%1").arg(id);
//            QTableWidgetItem *item = new QTableWidgetItem(value);
//            ui->tableWidget->setItem(i, 1, item);
//        }

//    }
//}

void MainWindow::file_init()
{
    QDir *temp = new QDir;
    bool exist = temp->exists(dir_str);
    if(exist) {
        //QMessageBox::warning(this,tr("创建文件夹"),tr("文件夹已经存在！"));
    } else {
        bool ok = temp->mkdir(dir_str);
        if( ok == false ) {
            QString s = QString("文件夹[%1]创建失败!").arg(dir_str);
            QMessageBox::warning(this,tr("创建文件夹"),tr(s.toUtf8()));
        }
    }

}

void MainWindow::control_disenable()
{
    //ui->choose_send_file->setEnabled(false);
    ui->choose_file->setEnabled(false);
    ui->switch_file->setEnabled(false);
    ui->send->setEnabled(false);
}

void MainWindow::control_enable()
{
    //ui->choose_send_file->setEnabled(true);
    ui->choose_file->setEnabled(true);
    ui->switch_file->setEnabled(true);
    ui->send->setEnabled(true);
}

//adb的回调函数
void MainWindow::onSearchFinished(int exit_code,QProcess::ExitStatus)
{
    //QString str = QString::fromLocal8Bit(process->readAll());
    qDebug() << "exit_code = " << exit_code;
    //ui->showlog->append(QString("exit_code = %1").arg(exit_code));
    QString str = process->readAll();
    qDebug() << "onSearchFinished str = " << str;
    //ui->showlog->append(str);
    str = str.simplified();

    switch(adb_code) {
    case IDLE:
            break;
    case VERSION:
        {
            if (str.contains("Android Debug Bridge version",Qt::CaseSensitive))
                //ui->showlog->append(QString("adb版本号 : %1").arg(str));
            m_usb_listener->EmitMySignal();     //手动触发一次
        }break;
    case STATUS:
        {
            //QString str = process->readAll();
            devices.clear();
            //device_num = 0;
            str = str.replace("List of devices attached","");
            //str = str.simplified();
            QStringList list = str.split(" ");

            int j = 0;
            for(int i = 0; i < list.count(); i++)
            {
                if (list.at(i) == "device") {
                    //device_num++;
                    QString s = QString("%1 %2").arg(list.at(i-1)).arg(list.at(i));
                    DEV dev;
                    dev.ID = list.at(i-1);
                    dev.status = SEND_IDLE;

                    QString str = QString("%1%2").arg(list.at(i)).arg(j++);
                    devices.insert(str,dev);
                    qDebug() <<i <<s<<endl;
                }
            }

            qDebug() << "有设备" << devices.keys().size();

            QPalette pa;
            if (devices.keys().size() == 0) {
                //pa.setColor(QPalette::WindowText,Qt::red);
                //ui->dev_status->setPalette(pa);

                //QMessageBox::warning(NULL, "提示", "没有连接设备", "确定");
                ui->dev_status->setText("device num [0]");
                ui->pushButton->setStyleSheet("background-color: rgb(211,211,211)");
               // control_disenable();
            } else {
                pa.setColor(QPalette::WindowText,Qt::black);
                ui->dev_status->setPalette(pa);
                QString Str = QString("device num [%1]").arg(devices.keys().size());
                ui->dev_status->setText(Str);
                ui->pushButton->setStyleSheet("background-color: rgb(152,251,152)");
                control_enable();
            }

            qDebug()<<"初始状态，哈希表";
            hash_traversal();
        }
        break;
     case WRITE:
        {

            dealed_num++;

            //根据exit_code设置上一次的处理结果
            set_hash_deal(exit_code);
            //hash_traversal();

            if (dealed_num == devices.keys().size()) {
                //发送广播指令
                sendbroadcast();

                qDebug() << "发送完成，哈希表此时的状态如下";
                hash_traversal();
                //showret *sendret = new showret(devices);
                //sendret->setParent(this);//指定父窗口，一般是目前将你弹出的窗口
                //sendret->exec();//模
                 showret sendret(language,devices);
                 sendret.exec();

//                 ui->send_status->setText("Ready to start!");
                 ui->status->setText("[ Current State  :  Ready to start! ]");

                 //ui->sendfile->setText("");
//                 send_filename = "./SendText/freq.txt";
//                 if (!ui->sfilename->text().isEmpty())
//                    ui->sfilename->setText("");
//                 ui->tableWidget->clear();


//                ui->tableWidget->setColumnCount(0);
//                ui->tableWidget->setRowCount(0);

                ui->send->setEnabled(true);

                //重置设备状态
                hash_reset();
            } else {
                adb_code = WRITE;
                //开始下一次的传输
                find_hash();
            }
        }
        break;
    case WIFI_CON:
        {
#if 0
            // 点击了connect
            if (ui->wifistatus->text().contains("not connected",Qt::CaseSensitive)) {
                qDebug() << "未连接";
                if (str.startsWith("connected to",Qt::CaseSensitive) || str.startsWith("already connected to",Qt::CaseSensitive)){
                   // QPalette pa;
                   // pa.setColor(QPalette::WindowText,Qt::green);
                   // ui->wifistatus->setPalette(pa);

                    ui->wifistatus->setText("status: [connected]");
                    ui->ip->setEnabled(false);
                    ui->port->setEnabled(false);
                    ui->connect->setEnabled(false);
                }
//                if (str.startsWith("already connected to",Qt::CaseSensitive)){
//                    QMessageBox::warning(NULL, "提示", "该设备已存在！", "确定");
//                }
            }
            else if (ui->wifistatus->text().contains("connected",Qt::CaseSensitive)) {
               // QPalette pa;
               // pa.setColor(QPalette::WindowText,Qt::red);
               // ui->wifistatus->setPalette(pa);
                if (str.isEmpty()) {
                    ui->wifistatus->setText("status: [not connected]");
                    ui->ip->setEnabled(true);
                    ui->port->setEnabled(true);
                    ui->connect->setEnabled(true);
                }
            }
#endif
           on_pushButton_clicked();

        }break;
      case READ:
        {
            if (exit_code != 0) {
                if (language == "English")
                    QMessageBox::warning(NULL, "prompt", "Read file failed!", "OK");

                if (language == "Chinese")
                    QMessageBox::warning(NULL, "提示", "读文件失败!", "确定");

                return;
            }

            ui->tableWidget->clear();
            ui->tableWidget->setColumnCount(0);
            ui->tableWidget->setRowCount(0);
//            ui->read_status->setText("Ready to start!");
            ui->status->setText("[ Current State  :  Ready to start! ]");
            table_init();

            QDir temDir("./RecvFile/recv.xls");
            QString absDir = temDir.absolutePath();

            qDebug()<<"绝对路径" <<absDir;

            QFile file(absDir);
            if (!file.exists()){
                if (language == "English")
                    QMessageBox::information(this,"prompt","file does not exist");
                if (language == "Chinese")
                    QMessageBox::information(this,"提示","文件不存在");

                return;
            }

            openExcel(absDir);


        }break;
    case BROADCOST:
        {
            if (exit_code == 0) {
                qDebug() << "发送广播指令成功!";
            } else
                qDebug() << "发送广播指令失败!";

        }break;
     case READBROADCOST:
        {
            if (exit_code == 0) {
                //ui->showlog->append("发送读取文件广播指令成功,开始轮询");

                QFile file("./RecvFile/recv.xls");
                if (file.exists())
                {
                    file.remove();
                    //ui->showlog->append("移除文件 : recv.xls");
                }

                //广播指令发送成功之后，开始轮询
                readpoll();
                //开启poll线程
                //ui->showlog->append("开启线程");
                pollTh->start();

            } else {
                //ui->showlog->append("发送读取文件广播指令失败!");
                ui->status->setText("[ Current State  :  Ready to start! ]");
            }

        }break;
     case POLL:
        {

            if (exit_code) {
                  //ui->showlog->append("没有读取到文件，继续...");
//                QString recvfile = "./RecvFile/flagfile.txt";
//                QString send_str = QString("adb -s %1 pull %2 %3").arg(revdevID).arg(flagfile_path).arg(recvfile);
//                waitsec++;
//                if (waitsec < MAXSEC) {
//                    QThread::sleep (1);
//                    ui->progressBar->setValue(waitsec);
//                    adb_code = POLL;
//                    process->start(send_str);
//                }
//                else {
//                    ui->progressBar->setValue(0);
//                    QMessageBox::warning(NULL, "prompt", "Read File Prepare TimeOut", "OK");
//                    ui->status->setText("[ Current State  :  Ready to start! ]");
//                    waitsec = 0;
//                }
            }
            else {
                //ui->showlog->append("读到文件，关闭线程，开始解析.");
                pollTh->terminate();

                ui->tableWidget->clear();
                ui->tableWidget->setColumnCount(0);
                ui->tableWidget->setRowCount(0);

                ui->areatable->clear();
                ui->areatable->setColumnCount(0);
                ui->areatable->setRowCount(0);
                ui->status->setText("[ Current State  :  Ready to start! ]");
                table_init();

                QDir temDir("./RecvFile/recv.xls");
                QString absDir = temDir.absolutePath();

                QString str = QString("绝对路径 %1").arg(absDir);
                //ui->showlog->append(str);

                QFile file(absDir);
                if (!file.exists()){
                    if (language == "English")
                        QMessageBox::information(this,"prompt","file does not exist");
                    if (language == "Chinese")
                        QMessageBox::information(this,"提示","文件不存在");

                    return;
                }

                ui->switch_file->setEnabled(false);

//                wTh->setImport();
//                wTh->getImportfilepath("./RecvFile/recv.xls");
//                wTh->start();
                setThreadImport(absDir);

               // ui->tableWidget->setEnabled(false);


               //openExcel(absDir);

//                QString recvfile = "./RecvFile/recv.xls";
//                QString send_file = QString("adb -s %1 pull %2 %3").arg(revdevID).arg(pull_path).arg(recvfile);
//                adb_code = READ;
//                process->start(send_file);
//                ui->status->setText("[ Current State  :  Reading... ]");
                ui->progressBar->setValue(0);
            }

        }break;
    }


}

void MainWindow::sendbroadcast()
{
    QString send;
    if (broadcast.isEmpty()) {
        send = "adb shell am broadcast -a com.yt.intercom.channel.change --es ChannelFilePath \"storage/sdcard0/Android/data/com.yt.intercom/channel_info_data.xls\"";
        QString info = QString("use default broadcast");
        //QMessageBox::warning(NULL, "提示", info, "确定");
    } else {
        send = broadcast;
    }

   send = broadcast;
   qDebug() << "发送广播指令" <<send;
   adb_code = BROADCOST;

   process->start(send);
}

void MainWindow::sendReadbroadcast()
{
    QString send;
    if (readbroadcast.isEmpty()) {
        send = "adb shell am broadcast -a com.yt.intercom.export.channel";
        QString info = QString("use default broadcast");
        //QMessageBox::warning(NULL, "提示", info, "确定");
    } else {
        send = readbroadcast;
    }

   send = readbroadcast;
   //qDebug() << "发送读取文件的广播指令" <<send;
   //ui->showlog->append("发送读取文件的广播指令");
   adb_code = READBROADCOST;

   process->start(send);
}

void MainWindow::on_pushButton_clicked()
{

   // process = new QProcess(this);
    adb_code = STATUS;
    process->start("adb devices");

   // adb_code = STATUS;
  //  connect(process,SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(onSearchFinished(int,QProcess::ExitStatus)));
}

int MainWindow::writedatatofile()
{
    QXlsx::Document xlsx(send_filename);/*打开一个book1的文件*/

    QXlsx::Format format;/*设置该单元的样式*/
    format.setBorderColor(QColor("#000000"));

    format.setFontSize(11);/*设置字体大小*/

    format.setVerticalAlignment(QXlsx::Format::AlignVCenter);
    format.setHorizontalAlignment(QXlsx::Format::AlignHCenter);/*横向居中*/

    xlsx.write("A1", "No");
    xlsx.write("B1", "AreaName");
    xlsx.write("C1", "ChannelSize");


    int col = ui->areatable->columnCount();
    int row = ui->areatable->rowCount();


    for (int i = 0; i < row; i++) {
        for (int j = 0; j < col; j++) {
            QString str = ui->areatable->item(i,j)->text();//取出字符串
            char ch = 'A' + j;
            QString index = QString("%1%2").arg(ch).arg(i+2);
            xlsx.write(index, str);
        }
    }

    if(!xlsx.selectSheet("Sheet2")){/*在当前打开的xlsx文件中，找一个名字为ziv的sheet*/
        xlsx.addSheet("Sheet2");//找不到的话就添加一个名为ziv的sheet
    }

    QString ctitile = "No#AreaNo#Channel Name#Channel Type#TX Frequency#RX Frequency#Color Code/Bandwidth#Power#Channel Mode/RX CTCSS Type#Call Type/RX CTCSS Code#Output Timeslot/TX CTCSS Type#Input Timeslot/TX CTCSS Code#Volume#Mic Gain/Mute";
    QStringList clist = ctitile.split("#");
   // qDebug() << "clist.size() = " <<clist.size();
    for (int i = 0; i < clist.size(); i++) {
        char ch = 'A' + i;
        QString index = QString("%1%2").arg(ch).arg(1);
        xlsx.write(index, clist.at(i));
    }

   // qDebug() << channels.keys().size();

    QMap<int,CHANNINFO>::iterator item;
    int j = 0;

    for(item = channels.begin(); item != channels.end(); ++item,j++) {

        QStringList tmp = item.value().AreaID.split("#");

        QString str = QString("%1#").arg(j) + tmp.at(0) + "#"
                + item.value().ChannelName + "#" + item.value().ChannelType + "#"
                + item.value().TXFrequency + "#" + item.value().RXFrequency + "#"
                + item.value().ColorCode + "#" + item.value().Power + "#"
                + item.value().ChannelMode + "#" + item.value().CallType + "#"
                + item.value().OutputTimeslot + "#" + item.value().InputTimeslot + "#"
                + item.value().Volume + "#" + item.value().MicGain + "#";

        QStringList list = str.split("#");
        //qDebug() << "str = " <<str;


        for (int i = 0; i < list.size(); i++) {
            char ch = 'A' + i;
            QString index = QString("%1%2").arg(ch).arg(j+2);
            xlsx.write(index, list.at(i));
        }
    }

    xlsx.saveAs(send_filename);/*保存*/

    //writetoExcel(ui->tableWidget,send_filename);
    return 0;
}

void MainWindow::on_send_clicked()
{
    export_write = false;
    if (push_path.isEmpty()) { //如果配置文件不存在，就出错
        if (language == "English")
             QMessageBox::warning(NULL, "prompt", "The config is not exist", "OK");
        if (language == "Chinese")
             QMessageBox::warning(NULL, "提示", "配置文件不存在", "确定");

//         ui->send_status->setText("Ready to start!");
         ui->status->setText("[ Current State  :  Ready to start! ]");
         return;
    }

    if (devices.keys().size() == 0) {
        if (language == "English")
             QMessageBox::warning(NULL, "prompt", "There is no device", "OK");
        if (language == "Chinese")
             QMessageBox::warning(NULL, "提示", "没有设备", "确定");

//          ui->send_status->setText("Ready to start!");
          ui->status->setText("[ Current State  :  Ready to start! ]");
        return;
    }

    int rowcount = ui->areatable->rowCount();
    if ((rowcount == 0) || (channels.keys().size() == 0)) {
        if (language == "English")
            QMessageBox::warning(NULL, "prompt", "There is no data", "OK");
        if (language == "Chinese")
            QMessageBox::warning(NULL, "提示", "没有数据", "确定");

//        ui->send_status->setText("Ready to start!");
        ui->status->setText("[ Current State  :  Ready to start! ]");
        return;
    }

    if (channelSelectRow != -1) {
        QString str = ui->tableWidget->item(channelSelectRow,2)->text();
        if (str.size() >= 18) {
            QString str1 = QString("The length of the [%1] is greater than 18").arg(str);
            QMessageBox::warning(NULL, "prompt", str1, "OK");
            return;
        }
    }

//    ui->send_status->setText("Sending...");
    //ui->showlog->append("[ Sending... ]");
    ui->status->setText("[ Current State  :  Sending... ]");
    this->repaint();

//    if (ui->sendfile->text() == send_filename) {
//        qDebug() << "使用默认的文件发送，将会把数据写入文件" << send_filename;
//        if (writedatatofile())
//            return;
//    } else {
//        qDebug() << "使用用户选择的文件发送" << ui->sendfile->text();
//    }

    QFile file("./SendText/sendfile.xls");
    if (file.exists())
    {
        file.remove();
        //ui->showlog->append("./SendText/sendfile.xls is exist and remove it.");
    }

     //把表格中的数据写入默认路径下的文件
//    if (writedatatofile())
//        return;

    QDir temDir("./SendText/sendfile.xls");
    QString absDir = temDir.absolutePath();

    export_write = true;
    exportFile_fileNmae(absDir);

    //ui->showlog->append("date is writed  -> ./SendText/sendfile.xls");

    return;
    //abc

    dealed_num = 0;
    find_hash();

    adb_code = WRITE;
    ui->send->setEnabled(false);
}

int MainWindow::on_choose_file_clicked()
{
    QString filepath = QFileDialog::getOpenFileName(NULL, "请选择数据文件", "", "(*.xls);;(*.xlsx)");
    if (filepath.isEmpty())
    {
        //QMessageBox::warning(NULL, "prompt", "not select file", "OK");
        return 1;
    }

//    if (filepath.isEmpty() && ui->sfilename->text().isEmpty())
//    {
//        //QMessageBox::warning(NULL, "prompt", "not select file", "OK");
//        return 1;
//    }

//    ui->tableWidget->clear();
//    ui->tableWidget->setColumnCount(0);
//    ui->tableWidget->setRowCount(0);


    if (!filepath.isEmpty())
      ui->sfilename->setText(filepath);
    //ui->showlog->append(QString("导入文件 %1").arg(filepath));
    //switch_flag = 0;
    return 0;
}

int MainWindow::showinfofileexist()
{
    QFile file("./ShowInfo/showinfo.txt");
    if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        if (language == "English") {
            QString str = QString("open file[%1]feiled!").arg("./ShowInfo/showinfo.txt");
            QMessageBox::warning(NULL, "prompt", str, "OK");
        }
        if (language == "Chinese") {
            QMessageBox::warning(NULL, "提示", "打开文件[showinfo.txt]失败", "确定");
        }

        return -1;
    }
    return 0;
}

void MainWindow::set_lable(QString info)
{
    //ui->import_status->setText(info);
    ui->status->setText("[ Current State  :   ]");
}
//转换
void MainWindow::on_switch_file_clicked()
{
    if (ui->sfilename->text().isEmpty()) {
        if (language == "English")
            QMessageBox::warning(NULL, "prompt", "Please select file", "OK");
        if (language == "Chinese")
            QMessageBox::warning(NULL, "提示", "请选择文件", "确定");

//        ui->import_status->setText("Ready to start!");
          ui->status->setText("[ Current State  :  Ready to start ]");
        return;
    }

//    ui->import_status->setText("Importing...");
    ui->status->setText("[ Current State  :  Importing... ]");
    this->repaint();

    ui->tableWidget->clear();
    ui->tableWidget->setColumnCount(0);
    ui->tableWidget->setRowCount(0);

    ui->areatable->clear();
    ui->areatable->setColumnCount(0);
    ui->areatable->setRowCount(0);
    table_init();

    QString filename = ui->sfilename->text();
    ui->switch_file->setEnabled(false);
   // ui->tableWidget->setEnabled(false);

    setThreadImport(filename);
//    wTh->setImport();
//    wTh->getImportfilepath(filename);
//    wTh->start();

//    int ret = openExcel(filename);
//    if (ret) {
//        if (ret == EMPTY) {
//            QMessageBox::warning(NULL, "prompt", "Import file is empty!", "OK");
//        }
//        if (ret == INFORMAT) {
//            QMessageBox::warning(NULL, "prompt", "Import file is Invalid format!", "OK");
//        }
//        ui->status->setText("[ Current State  :  Ready to start! ]");
//        return;

//    }

//    QString str = QString("Import file successful!");
//    QMessageBox::warning(NULL, str, "OK");
//    ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows); //设置选择行为，以行为单位
//    ui->tableWidget->setSelectionMode(QAbstractItemView::SingleSelection); //设置选择模式，选择单行
//    ui->status->setText("[ Current State  :  Ready to start! ]");

}

void MainWindow::setThreadImport(QString filename)
{
    wTh->setImport();
    wTh->getImportfilepath(filename);
    wTh->start();
}

//void MainWindow::on_choose_send_file_clicked()
//{
//    QString filepath = QFileDialog::getOpenFileName(NULL, "请选择数据文件", "", "(*.xls);;(*.xlsx)");
//    if (filepath.isEmpty())
//    {
//        if (!ui->sendfile->text().isEmpty()) {
//            QMessageBox::warning(NULL, "prompt", "Use default file", "OK");
//            return;
//        } else {
//            QMessageBox::warning(NULL, "prompt", "Not select file", "OK");
//            return;
//        }

//    }
//    //ui->sendfile->setText(filepath);

//    //使用选择的文件发送
//    //send_filename = filepath;
//}



//#####################################################################################

QVariant MainWindow::readAll(QAxObject *sheet)
{
    QVariant var;
    if (sheet != NULL && !sheet->isNull())
    {
        QAxObject *usedRange = sheet->querySubObject("UsedRange");
        if (NULL == usedRange || usedRange->isNull())
        {
            return var;
        }
        var = usedRange->dynamicCall("Value");
        delete usedRange;
    }
    return var;
}


int MainWindow::openExcel(QString fileName)
{
    int ret = 0;
    QAxObject excel("Excel.Application");
    excel.setProperty("Visible", false);
    QAxObject *work_books = excel.querySubObject("WorkBooks");
    work_books->dynamicCall("Open(const QString&)", fileName);

    QAxObject *work_book = excel.querySubObject("ActiveWorkBook");
    QAxObject *work_sheets = work_book->querySubObject("Sheets");  //Sheets也可换用WorkSheets

    int sheet_count = work_sheets->property("Count").toInt();  //获取工作表数目
    //qDebug() << "sheet_count = " << sheet_count;
    if (sheet_count > 0)
    {
        QAxObject *work_sheet = work_book->querySubObject("Sheets(int)", 1);

        //qDebug() << "文件数据读取中...";
        QVariant var = readAll(work_sheet);
        ret = castVariant2ListListVariant(var);
    }

    work_book->dynamicCall("Close(Boolean)", false);  //关闭文件
    excel.dynamicCall("Quit(void)");  //退出
    ui->switch_file->setEnabled(true);
    //qDebug() << "ret = " <<ret;
    return ret;
}


int MainWindow::castVariant2ListListVariant(const QVariant &var)
{
    QVariantList varRows = var.toList();
    if (varRows.isEmpty())
    {
        return EMPTY;
    }

    const int rowCount = varRows.size();
    //qDebug()<<"================="<<rowCount;
    QVariantList rowData;
    for (int i = 0; i < rowCount; ++i)
    {
        //qDebug() << i;
        rowData = varRows[i].toList();
        if (i == 0)
        {
            QStringList header;
            foreach (auto item , rowData)
            {
                QString value = item.toString();
                header.append(value);
            }

            if (header.size() != headers.size())
                return INFORMAT;

            ui->tableWidget->clear();
            ui->tableWidget->setColumnCount(0);
            ui->tableWidget->setRowCount(0);
            table_init();

            //ui->tableWidget->setColumnCount(headers.size()); //设置列数
            //ui->tableWidget->setHorizontalHeaderLabels(headers);
//            for (int x = 0; x < headers.size(); x++)
//            ui->tableWidget->horizontalHeader()->setSectionResizeMode(x,QHeaderView::ResizeToContents);
//            ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);

//            qDebug() <<"xxxxxxx";
//            for (int i; i < headers.size(); i++) {
//                //if (!header.at(i).contains(headers.at(i)) || !headers.at(i).contains(header.at(i)))
//                //    return INFORMAT;
//                if (header.at(i).contains(headers.at(i)))
//                    qDebug() <<"yes";
//            }
        }
        else
        {
            //qDebug() << "rowData.size() = " <<rowData.size();
            int j;
            for (j = 0; j < rowData.size(); j++) {
                if (!rowData[j].toString().isEmpty())
                    break;
            }

            if (j == rowData.size()) {
                //qDebug() << "跳过空行";
                continue;
            }

           // qDebug() << "读取数据";

            int row = ui->tableWidget->rowCount();
            //qDebug() <<row << rowData.size();
            ui->tableWidget->setRowCount(row + 1);

            for (int j = 0; j < rowData.size(); j++)
            {
                QString value = rowData[j].toString();
                //qDebug() << value;
                QTableWidgetItem *item = new QTableWidgetItem(value);
                ui->tableWidget->setItem(row, j, item);
                //ui->tableWidget->item(row,j)->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);

            }
        }
    }

//    int col = ui->tableWidget->columnCount();
//    int row = ui->tableWidget->rowCount();
//    ui->tableWidget->insertRow(row);

//    for (int i = 0; i < col; i++) {
//        QString value = "";
//        QTableWidgetItem *item = new QTableWidgetItem(value);
//        ui->tableWidget->setItem(row, i, item);
//        ui->tableWidget->item(row,i)->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
//    }
//    file.close();
    //显示默认文件
    //ui->sendfile->setText(send_filename);
    return OK;
}

void MainWindow::clear_file(QString filepath)
{
    QFileInfo fileInfo(filepath);
    if(!fileInfo.isFile())
    {
        //文件不存在直接返回
        //qDebug() << file_str  << "file is not exist!";
        return;
    }

    QFile file(filepath);
    file.open(QFile::WriteOnly|QFile::Truncate);
    file.close();
}

//遍历哈希表
int MainWindow::find_hash()
{

    QHash<QString,DEV>::iterator i;
    int j = 0;

    QString file = send_filename;
    for(i = devices.begin(); i != devices.end(); ++i,j++) {
        if (i.value().status == SEND_IDLE) {
            QString str = QString("writr ID [%1],and status [%2]").arg(i.value().ID).arg(i.value().status);
            //ui->showlog->append(str);
            qDebug() << "  发送的ID " << i.value().ID << "此时的状态" << i.value().status;
            //ui->showlog->append(QString("发送的ID %1 此时的状态 %2").arg(i.value().ID).arg(i.value().status));
            //qDebug() << "push_path = push_path"<<push_path;
            QString send_file = QString("adb -s %1 push %2 %3").arg(i.value().ID).arg(file).arg(push_path);
            qDebug() << "send_file = "<<send_file;
            //ui->showlog->append(send_file);
            i.value().status = SEND_DEAL;
            process->start(send_file);
            break;
        }
    }


   // qDebug() << "j = " <<j;

    if (j == devices.keys().size() - 1) {
        return 1;
    }
    return 0;

}

void MainWindow::set_hash_deal(int exit_code)
{

    QHash<QString, DEV>::iterator i;

    for(i = devices.begin(); i != devices.end(); ++i) {
        if (i.value().status == SEND_DEAL) {
            if (exit_code) //失败
                i.value().status = SEND_FAIL;
            else
                i.value().status = SEND_SUCCESS;
            break;
        }
    }

}

void MainWindow::hash_reset()
{

    QHash<QString, DEV>::iterator i;

    for(i = devices.begin(); i != devices.end(); ++i) {
            i.value().status = SEND_IDLE;
    }

}

void MainWindow::hash_traversal()
{
     QHash<QString, DEV>::iterator i;
    for(i = devices.begin(); i != devices.end(); ++i) {
         qDebug() << i.key() <<"        " << i.value().ID <<"  "  <<i.value().status;
     }

}

int MainWindow::wifidevice_exist(QString ID)
{
   QHash<QString, DEV>::iterator i;
   for(i = devices.begin(); i != devices.end(); ++i) {
        //qDebug() << i.key() <<"        " << i.value().ID <<"  "  <<i.value().status;
       if (i.value().ID == ID)
           return 1;
   }
   return 0;
}

//要删除的功能
void MainWindow::on_connect_clicked()
{
#if 0
    if (ui->ip->text().isEmpty() || ui->port->text().isEmpty()) {
        QMessageBox::warning(NULL, "prompt", "Please enter the information and connect", "OK");
        return;
    }

//    QString ID = QString("%1:%2").arg(ui->ip->text()).arg(ui->port->text());
//    if (wifidevice_exist(ID)) {
//        QMessageBox::warning(NULL, "提示", "该设备已经存在", "确定");
//        return;
//    }

    //adb connect ip:port
    QString str = QString("adb connect %1:%2").arg(ui->ip->text()).arg(ui->port->text());
    process->start(str);
    adb_code = WIFI_CON;
#endif
}

//要删除的功能
void MainWindow::on_disconnect_clicked()
{
#if 0
    if (ui->wifistatus->text().contains("connected",Qt::CaseSensitive)) {
        //adb connect ip:port
        QString str = QString("adb disconnect %1:%2").arg(ui->ip->text()).arg(ui->port->text());
        process->start(str);
        adb_code = WIFI_CON;
    } else {
        QMessageBox::warning(NULL, "prompt", "Not connected yet", "OK");
    }
#endif
}

//ADD D 数字
void MainWindow::on_pushButton_2_clicked()
{
    //qDebug() <<" ---" <<SelectRowID;
    if (ui->areatable->rowCount() == 0)
        SelectRowID = -1;

    if (SelectRowID == -1) {
        if (language == "English")
            QMessageBox::warning(NULL, "prompt", "Please select area table", "OK");

        if (language == "Chinese")
            QMessageBox::warning(NULL, "提示", "请先选择区域", "确定");

        return;
    }

    ADD_D_CH *d_ch = new ADD_D_CH(language, FREQ_LIST[freq]);
    connect(d_ch,SIGNAL(send_str(QString)),this,SLOT(deal_add_d_ch(QString)));

    d_ch->exec();
    return;

    int col = ui->tableWidget->columnCount();
    int row = ui->tableWidget->rowCount();

    //qDebug() << "col = " << col << "row = " << row;

    CHANNINFO chanelinfo;
    //chanelinfo.AreaID = SelectRowID;

    QString str;
    int id;

    if (row == 0) {
        id = 1;
    } else {
        //qDebug() << "id = " <<ui->channeltable->item(row-1,0)->text();//取出字符串
        id = ui->tableWidget->item(row-1,0)->text().toInt() + 1;
    }

    str += QString("%1#").arg(id);

    str += QString("%1#").arg(SelectRowID);
    //str += "CH Name#";
    str += QString("Digital Channel%1#").arg(id);
    chanelinfo.ChannelName = QString("Digital Channel%1").arg(id);

    QString type = "D";
    str += type + "#";
    chanelinfo.ChannelType = "D";

    QString tx = FREQ_LIST[freq];
    str += tx + "#";
    chanelinfo.TXFrequency = FREQ_LIST[freq];

    QString rx = FREQ_LIST[freq];
    str += rx + "#";
    chanelinfo.RXFrequency = FREQ_LIST[freq];

    QString color = "0";
    str += color + "#";
    chanelinfo.ColorCode = "0";

    QString power = "1";
    str += power + "#";
    chanelinfo.Power = "1";

    QString channel_mode = "1";
    str += channel_mode + "#";
    chanelinfo.ChannelMode = "1";

    QString call_type = "2";
    str += call_type + "#";
    chanelinfo.CallType = "2";

    QString output_time = "1";
    str += output_time + "#";
    chanelinfo.OutputTimeslot = "1";

    QString input_time = "1";
    str += input_time + "#";
    chanelinfo.InputTimeslot = "1";

    QString volume = "6";
    str += volume + "#";
    chanelinfo.Volume = "6";

    QString gain = "4";
    str += gain + "#";
    chanelinfo.MicGain = "4";

    ui->tableWidget->insertRow(row);

    QStringList list = str.split("#");

    QString sId = QString("%1#%2#").arg(SelectRowID).arg(id);
    chanelinfo.AreaID = sId;
    channels.insert(channels.keys().size(),chanelinfo);

    //qDebug() << "AreaID = " << chanelinfo.AreaID;
    //qDebug() << "str = " <<str;

    for (int i = 0; i < list.count()-1; i++) {
        //qDebug() << list.at(i);
        QTableWidgetItem *item = new QTableWidgetItem(list.at(i));
        if (i == 0 || i == 1)
            item->setFlags(item->flags() & (~Qt::ItemIsEditable));
        ui->tableWidget->setItem(row, i, item);
    }
    Updatechannels(SelectRowID);
    //qDebug() << "Add D CH " << channels.keys().size();
    return;


//    int col = ui->tableWidget->columnCount();
//    int row = ui->tableWidget->rowCount();

//    qDebug() << "col = " << col << "row = " << row;


//     QString str;
//    int id;

//    if (row == 0) {
//        id = 1;
//        //str += "1";
//        //str += "#";
//    } else {
//        qDebug() << "id = " <<ui->tableWidget->item(row-1,0)->text();//取出字符串
//        id = ui->tableWidget->item(row-1,0)->text().toInt() + 1;
//        //QString id = QString("%1").arg(ui->tableWidget->item(row-1,0)->text().toInt() + 1);
//        //str += id + "#";
//    }

//    str += QString("%1#").arg(id);

//    str += QString("1#");

//    //str += "CH Name#";
//    str += QString("Channel%1#").arg(id);

//    QString type = "D";
//    str += type + "#";

//    QString tx = "401.02500";
//    str += tx + "#";

//    QString rx = "401.02500";
//    str += rx + "#";

//    QString color = "0";
//    str += color + "#";

//    QString power = "1";
//    str += power + "#";

//    QString channel_mode = "1";
//    str += channel_mode + "#";

//    QString call_type = "2";
//    str += call_type + "#";

//    QString output_time = "1";
//    str += output_time + "#";

//    QString input_time = "1";
//    str += input_time + "#";

//    QString volume = "6";
//    str += volume + "#";

//    QString gain = "4";
//    str += gain + "#";

//    ui->tableWidget->insertRow(row);

//    QStringList list = str.split("#");
//    qDebug() << list.count();

//    for (int i = 0; i < list.count()-1; i++) {
//        QTableWidgetItem *item = new QTableWidgetItem(list.at(i));
//        //qDebug() << list.at(i);
//        ui->tableWidget->setItem(row, i, item);
//        //ui->tableWidget->item(row,i)->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
//    }
}

//添加模拟信号
void MainWindow::on_pushButton_3_clicked()
{
    if (ui->areatable->rowCount() == 0)
        SelectRowID = -1;

    if (SelectRowID == -1) {
        if (language == "English")
            QMessageBox::warning(NULL, "prompt", "Please select area table", "OK");
        if (language == "Chinese")
            QMessageBox::warning(NULL, "提示", "请先选择区域", "确定");

        return;
    }

    ADD_A_CH *a_ch = new ADD_A_CH(language, FREQ_LIST[freq]);
    connect(a_ch,SIGNAL(send_str(QString)),this,SLOT(deal_add_a_ch(QString)));

    a_ch->exec();
    return;


    int col = ui->tableWidget->columnCount();
    int row = ui->tableWidget->rowCount();

    CHANNINFO chanelinfo;
    QString str;
        int id;

       if (row == 0) {
           id = 1;
       } else {
           //qDebug() << "id = " <<ui->channeltable->item(row-1,0)->text();//取出字符串
           id = ui->tableWidget->item(row-1,0)->text().toInt() + 1;
       }

       str += QString("%1#").arg(id);

       str += QString("%1#").arg(SelectRowID);

       str += QString("Analog Channel%1#").arg(id);
       chanelinfo.ChannelName = QString("Analog Channel%1").arg(id);

       QString type = "A";
        str += type + "#";
        chanelinfo.ChannelType = "A";

        QString tx = FREQ_LIST[freq];
        str += tx + "#";
        chanelinfo.TXFrequency = FREQ_LIST[freq];

        QString rx = FREQ_LIST[freq];
        str += rx + "#";
         chanelinfo.RXFrequency = FREQ_LIST[freq];

        QString Bandwidth = "2";
        str += Bandwidth + "#";
        chanelinfo.ColorCode = "2";

        QString power = "1";
        str += power + "#";
         chanelinfo.Power = "1";

        QString RX_CTCSS_Type = "1";
        str += RX_CTCSS_Type + "#";
        chanelinfo.ChannelMode = "1";

        QString RX_CTCSS_Code = "0";
        str += RX_CTCSS_Code + "#";
        chanelinfo.CallType = "0";

        QString TX_CTCSS_Type = "1";
        str += TX_CTCSS_Type + "#";
        chanelinfo.OutputTimeslot = "1";

        QString TX_CTCSS_Code = "0";
        str += TX_CTCSS_Code + "#";
        chanelinfo.InputTimeslot = "0";

        QString volume = "6";
        str += volume + "#";
        chanelinfo.Volume = "6";

        QString gain = "4";
        str += gain + "#";
        chanelinfo.MicGain = "4";
        //qDebug() << "+++" <<str;

        ui->tableWidget->insertRow(row);

        QStringList list = str.split("#");

        QString sId = QString("%1#%2#").arg(SelectRowID).arg(id);
        chanelinfo.AreaID = sId;
        channels.insert(channels.keys().size(),chanelinfo);


        for (int i = 0; i < col; i++) {
            QTableWidgetItem *item = new QTableWidgetItem(list.at(i));
            if (i == 0 || i == 1)
                item->setFlags(item->flags() & (~Qt::ItemIsEditable));
            ui->tableWidget->setItem(row, i, item);
            //ui->tableWidget->item(row,i)->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
        }
        Updatechannels(SelectRowID);
        // qDebug() << "Add A CH " << channels.keys().size();
    return;


//    int col = ui->tableWidget->columnCount();
//    int row = ui->tableWidget->rowCount();


//    QString str;
//    int id;

//   if (row == 0) {
//       id = 1;
//       //str += "1";
//       //str += "#";
//   } else {
//       qDebug() << "id = " <<ui->tableWidget->item(row-1,0)->text();//取出字符串
//       id = ui->tableWidget->item(row-1,0)->text().toInt() + 1;
//       //QString id = QString("%1").arg(ui->tableWidget->item(row-1,0)->text().toInt() + 1);
//       //str += id + "#";
//   }

//   str += QString("%1#").arg(id);

//   str += QString("1#");
//   str += QString("Channel%1#").arg(id);
//   //str += "CH Name#";

//    QString type = "A";
//    str += type + "#";

//    QString tx = "401.02500";
//    str += tx + "#";

//    QString rx = "401.02500";
//    str += rx + "#";

//    QString Bandwidth = "2";
//    str += Bandwidth + "#";

//    QString power = "1";
//    str += power + "#";

//    QString RX_CTCSS_Type = "1";
//    str += RX_CTCSS_Type + "#";

//    QString RX_CTCSS_Code = "0";
//    str += RX_CTCSS_Code + "#";

//    QString TX_CTCSS_Type = "1";
//    str += TX_CTCSS_Type + "#";

//    QString TX_CTCSS_Code = "0";
//    str += TX_CTCSS_Code + "#";

//    QString volume = "6";
//    str += volume + "#";

//    QString gain = "4";
//    str += gain + "#";

//    ui->tableWidget->insertRow(row);

//    QStringList list = str.split("#");

//    for (int i = 0; i < col; i++) {
//        QTableWidgetItem *item = new QTableWidgetItem(list.at(i));
//        ui->tableWidget->setItem(row, i, item);
//        //ui->tableWidget->item(row,i)->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
//    }
}

void MainWindow::on_clean_clicked()
{
    //qDebug() << "SelectRowID = " <<SelectRowID ;
    //总共多少行
    channelSelectRow = -1;
    int rowcount = ui->tableWidget->rowCount();

    if (rowcount == 0)
        return;

    //ui->showlog->append(QString("点击了[信道清除按钮]，清除第[%1]个区域的信道").arg(SelectRowID));
    //qDebug() << "----------------";

    ui->tableWidget->clear();
    ui->tableWidget->setColumnCount(0);
    ui->tableWidget->setRowCount(0);
    table_init();

    //把所选区域ID对应的信道全部删除
    QMap<int,CHANNINFO>::iterator  i;
    for(i = channels.begin(); i != channels.end();) {
        QStringList tmp = i.value().AreaID.split("#");
        QString aid = tmp.at(0);
        if (aid.toInt() == (SelectRowID)) {
            //qDebug() << "删除";
            i = channels.erase(i);
        }
        else {
            i++;
        }
    }

    //qDebug() <<"删除之后还有多少" <<channels.keys().size();

    //清除完之后个数直接等于0
    //int aid = ui->areatable->item(SelectRowID-1,0)->text().toInt();
    //qDebug() <<"aid = " <<aid;
    //Updatechannels(aid);

    //交换
    channelsTemp.clear();
    for(i = channels.begin(); i != channels.end();) {
        channelsTemp.insert(channelsTemp.keys().size(),i.value());
        i++;
    }
    channels.clear();
    channels = channelsTemp;

    Updatechannels(SelectRowID);
    //ui->showlog->append("更新状态 ... Done");
    return;
    //switch_flag = 0;
    ui->tableWidget->clear();
    ui->tableWidget->setColumnCount(0);
    ui->tableWidget->setRowCount(0);
    table_init();
}

void MainWindow::Updatechannels(int row)
{
    //qDebug() << "row = " << row;
    QMap<int,CHANNINFO>::iterator  i;
    int num = 0;

    for(i = channels.begin(); i != channels.end();) {
        QStringList tmp = i.value().AreaID.split("#");
        QString aid = tmp.at(0);
        if (aid.toInt() == (row)) {
            num++;
        }
        i++;
    }

    //qDebug() << "num = " <<num;

    //QString str = ui->areatable->item(SelectRowID-1,2)->text();//取出字符串
    QTableWidgetItem *item = new QTableWidgetItem(QString("%1").arg(num));
    item->setFlags(item->flags() & (~Qt::ItemIsEditable));
    ui->areatable->setItem(row-1, 2, item);

}

void MainWindow::on_read_clicked()
{
    revdevID = "";

    if (pull_path.isEmpty()) { //如果配置文件不存在，就出错
        if (language == "English")
             QMessageBox::warning(NULL, "prompt", "The config is not exist", "OK");
        if (language == "Chinese")
             QMessageBox::warning(NULL, "提示", "配置文件不存在", "确定");

         return;
    }

    //没有设备，退出
    if (devices.keys().size() == 0) {
        if (language == "English")
            QMessageBox::warning(NULL, "prompt", "There is no device", "OK");

        if (language == "Chinese")
            QMessageBox::warning(NULL, "提示", "没有设备", "确定");

        return;
    }

    //选择一个设备进行读取

    // ui->showlog->append("[ Reading... ]");
    ui->status->setText("[ Current State  :  Reading... ]");
//    rfile = new Readfile(devices);

//    connect(rfile,SIGNAL(sendId(int)),this,SLOT(recvId(int)));
//    connect(rfile,SIGNAL(wclose()),this,SLOT(deal_wclose()));
    rfile->recvdev(language,devices);
    rfile->exec();//模
}

void MainWindow::deal_wclose()
{
//    ui->read_status->setText("Ready to start!");
    ui->status->setText("[ Current State  :  Ready to start! ]");
}

void MainWindow::recvId(int id)
{
    //qDebug() <<"收到ID" <<id;
    QString str = QString("recv Id is %1").arg(id);
    //ui->showlog->append(str);

    QHash<QString,DEV>::iterator i;
    int j  = 0;

    //QString revdevID;
    for(i = devices.begin(); i != devices.end(); ++i) {
        if (j++ == id) {
            QString str = QString("Corresponding device ID %1").arg(i.value().ID);
            //ui->showlog->append(str);
            //qDebug() <<"对应的ID为"<< i.value().ID;
            revdevID = i.value().ID;
            break;
        }
    }

    if (revdevID.isEmpty())
        return;

    //收到了要读取文件的设备ID，先发送广播指令
    ui->status->setText("[ Current State  :  Ready Prepare... ]");
    sendReadbroadcast();

#if 0
    //新建文件夹
    QDir *photo = new QDir;
    bool exist = photo->exists("./RecvFile");
    if(!exist)
    {
       photo->mkdir("./RecvFile");
    }

    //QString recvfile = "./RecvFile/recv.xls";
    QString recvfile = "./RecvFile/flagfile.txt";

    if (pull_path.isEmpty()) { //如果配置文件不存在，就出错
         QMessageBox::warning(NULL, "prompt", "The config is not exist", "OK");
         return;
    }

    QString send_file = QString("adb -s %1 pull %2 %3").arg(revdevID).arg(flagfile_path).arg(recvfile);
    //qDebug()<<send_file;
    adb_code = POLL;
    process->start(send_file);
//    ui->read_status->setText("Ready Prepare!");
    ui->status->setText("[ Current State  :  Ready Prepare... ]");
#endif
}

void MainWindow::readpoll()
{

    QString recvfile = "./RecvFile/recv.xls";

    if (pull_path.isEmpty()) { //如果配置文件不存在，就出错
        if (language == "English")
             QMessageBox::warning(NULL, "prompt", "The config is not exist", "OK");
        if (language == "Chinese")
             QMessageBox::warning(NULL, "提示", "配置文件不存在", "确定");

         return;
    }

    QString send_file = QString("adb -s %1 pull %2 %3").arg(revdevID).arg(pull_path).arg(recvfile);
    //QString send_file = QString("adb -s %1 pull %2 %3").arg(revdevID).arg(flagfile_path).arg(recvfile);
    adb_code = POLL;
    ui->status->setText("[ Current State  :  Ready Prepare... ]");
    process->start(send_file);
}




//增加区域
void MainWindow::on_addarea_clicked()
{
    int col = ui->areatable->columnCount();
    int row = ui->areatable->rowCount();

     QString str;
    int id;

    if (row == 0) {
        id = 1;
    } else {
        id = ui->areatable->item(row-1,0)->text().toInt() + 1;
    }

    str += QString("%1#").arg(id);

    //str += "CH Name#";
    str += QString("Area%1#").arg(id);

    int size = 0;
    str += QString("%1#").arg(size);


    ui->areatable->insertRow(row);

    QStringList list = str.split("#");
    for (int i = 0; i < list.count()-1; i++) {
        QTableWidgetItem *item = new QTableWidgetItem(list.at(i));
        if (i == 0 || i == 2)
            item->setFlags(item->flags() & (~Qt::ItemIsEditable));
        ui->areatable->setItem(row, i, item);
    }

    QModelIndex index = ui->areatable->model()->index(row,0);
    onTableClicked(index);
}

void MainWindow::on_cleanarea_clicked()
{
    //qDebug() <<ui->areatable->rowCount();
    if (ui->areatable->rowCount() == 0) {
        SelectRowID == -1;
        return;
    }

    ui->areatable->clear();
    ui->areatable->setColumnCount(0);
    ui->areatable->setRowCount(0);

    ui->tableWidget->clear();
    ui->tableWidget->setColumnCount(0);
    ui->tableWidget->setRowCount(0);
    table_init();

    channels.clear();
    SelectRowID == -1;
    //qDebug() <<ui->areatable->rowCount();
}

//处理数字通道
void MainWindow::deal_add_d_ch(QString strv)
{
    qDebug() << "add_d_ch传回的数据为" <<strv;
    QStringList slist = strv.split("#");
    //for (int i = 0; i < slist.size(); i++)
    //    qDebug() << QString("%1").arg(slist.at(i));

    int col = ui->tableWidget->columnCount();
    int row = ui->tableWidget->rowCount();
    qDebug() << col << row;

    CHANNINFO chanelinfo;

    QString str;
    int id;

    if (row == 0) {
        id = 1;
    } else {
        id = ui->tableWidget->item(row-1,0)->text().toInt() + 1;
    }

    str += QString("%1#").arg(id);

    str += QString("%1#").arg(SelectRowID);

    //str += QString("Digital Channel%1#").arg(id);
    //chanelinfo.ChannelName = QString("Digital Channel%1").arg(id);

    //信道名称
    QString name = QString("%1").arg(slist.at(0));
     str += name + "#";
    chanelinfo.ChannelName = name;

    //类型
    QString type = "D";
    str += type + "#";
    chanelinfo.ChannelType = type;

    //发射频率
    QString tx = QString("%1").arg(slist.at(2));
    str += tx + "#";
    chanelinfo.TXFrequency = tx;

    //接收频率
    QString rx = QString("%1").arg(slist.at(1));
    str += rx + "#";
    chanelinfo.RXFrequency = rx;

    //色码
    QString color = QString("%1").arg(slist.at(5));
    str += color + "#";
    chanelinfo.ColorCode = color;

    //功率 1代表高功率，0代表低功率, 默认1(高功率)
    QString power;
    if (language == "Chinese")
    {
        if (QString("%1").arg(slist.at(4)) == "高")
            power = "1";
        else if (QString("%1").arg(slist.at(4)) == "低")
            power = "0";
    }
    if (language == "English")
    {
        if (QString("%1").arg(slist.at(4)) == "High")
            power = "1";
        else if (QString("%1").arg(slist.at(4)) == "Low")
            power = "0";
    }

    str += power + "#";
    chanelinfo.Power = power;

    //信道模式 1代表直通模式，2代表双时隙模式
    QString channel_mode;
    if (language == "Chinese")
    {
        if ((QString("%1").arg(slist.at(6)) == "直通模式"))
            channel_mode = "1";
        else if ((QString("%1").arg(slist.at(6)) == "真双时隙模式"))
            channel_mode = "2";
    }
    if (language == "English")
    {
        if ((QString("%1").arg(slist.at(6)) == "Direct-Mode"))
            channel_mode = "1";
        else if ((QString("%1").arg(slist.at(6)) == "Double-timeslot"))
            channel_mode = "2";
    }

    str += channel_mode + "#";
    chanelinfo.ChannelMode = channel_mode;

    //呼叫类型 1-个呼，2-组呼，3-全呼，4-双工，默认2-组呼
    QString call_type;
    if (language == "Chinese")
    {
        if ((QString("%1").arg(slist.at(7)) == "个呼"))
            call_type = "1";
        else if ((QString("%1").arg(slist.at(7)) == "组呼"))
            call_type = "2";
        else if ((QString("%1").arg(slist.at(7)) == "全呼"))
            call_type = "3";
    }
    if (language == "English")
    {
        if ((QString("%1").arg(slist.at(7)) == "Private"))
            call_type = "1";
        else if ((QString("%1").arg(slist.at(7)) == "Group"))
            call_type = "2";
        else if ((QString("%1").arg(slist.at(7)) == "All"))
            call_type = "3";
    }

    str += call_type + "#";
    chanelinfo.CallType = call_type;

    //输出时隙 1-“时隙1”,2-“时隙2
    QString output_time;
    if (language == "Chinese")
    {
        if ((QString("%1").arg(slist.at(8)) == "时隙1"))
            output_time = "1";
        else if ((QString("%1").arg(slist.at(8)) == "时隙2"))
            output_time = "2";
    }
    if (language == "English")
    {
        if ((QString("%1").arg(slist.at(8)) == "Slot1"))
            output_time = "1";
        else if ((QString("%1").arg(slist.at(8)) == "Slot2"))
            output_time = "2";
    }

    str += output_time + "#";
    chanelinfo.OutputTimeslot = output_time;

    //输入时隙 1-“时隙1”,2-“时隙2”
    QString input_time;
    if (language == "Chinese")
    {
        if ((QString("%1").arg(slist.at(9)) == "时隙1"))
            input_time = "1";
        else if ((QString("%1").arg(slist.at(9)) == "时隙2"))
            input_time = "2";
    }
    if (language == "English")
    {
        if ((QString("%1").arg(slist.at(9)) == "Slot1"))
            input_time = "1";
        else if ((QString("%1").arg(slist.at(9)) == "Slot2"))
            input_time = "2";
    }

    str += input_time + "#";
    chanelinfo.InputTimeslot = input_time;

    //音量
    QString volume = QString("%1").arg(slist.at(10));
    str += volume + "#";
    chanelinfo.Volume = volume;

    //增益
    QString gain = QString("%1").arg(slist.at(11));
    str += gain + "#";
    chanelinfo.MicGain = gain;

    //本地ID
    QString Id = QString("%1").arg(slist.at(3));
    str += Id + "#";
    chanelinfo.Id = Id;
    qDebug() << "ID = " << Id;

    //联系人号码
    QString num = QString("%1").arg(slist.at(12));
    str += num + "#";
    chanelinfo.num = num;

    //呼叫列表
    QString llist = QString("%1").arg(slist.at(13));
    str += llist + "#";
    chanelinfo.list = llist;

    //密钥
    QString key = QString("%1").arg(slist.at(14));
    str += key + "#";
    chanelinfo.key = key;

    //加密
    QString encrypt;
    if (language == "English")
    {
        if (QString("%1").arg(slist.at(15)) == "Open")
            encrypt = "1";
        else if (QString("%1").arg(slist.at(15)) == "Close")
            encrypt = "0";
    }
    if (language == "Chinese")
    {
        if (QString("%1").arg(slist.at(15)) == "开")
            encrypt = "1";
        else if (QString("%1").arg(slist.at(15)) == "关")
            encrypt = "0";
    }
    str += encrypt + "#";
    chanelinfo.encrypt = encrypt;


    ui->tableWidget->insertRow(row);

    qDebug() << "组装好的数据为" <<str;

    QStringList list = str.split("#");

    QString sId = QString("%1#%2#").arg(SelectRowID).arg(id);
    chanelinfo.AreaID = sId;
    channels.insert(channels.keys().size(),chanelinfo);

    qDebug() << "channels的大小为" <<channels.keys().size() << list.count();
    QMap<int,CHANNINFO>::iterator  i;
    for(i = channels.begin(); i != channels.end();i++) {
        qDebug() << "channels数据为"<<i.value().AreaID << i.value().ChannelName << i.value().ChannelType
                 <<i.value().TXFrequency<<i.value().RXFrequency<<i.value().ColorCode<<i.value().Power
                 <<i.value().ChannelMode<<i.value().CallType<<i.value().OutputTimeslot<<i.value().InputTimeslot
                 <<i.value().Volume<<i.value().MicGain;

    }

    for (int i = 0; i < list.count()-1; i++) {
        qDebug() << "添加数据" << QString("%1").arg(list.at(i));
        QTableWidgetItem *item = new QTableWidgetItem(list.at(i));
        if (i == 0 || i == 1)
            item->setFlags(item->flags() & (~Qt::ItemIsEditable));
        ui->tableWidget->setItem(row, i, item);
        qDebug() <<"11111->" <<ui->tableWidget->item(row,i)->text();
    }

    for (int i = 0; i < ui->tableWidget->columnCount(); i++)
        qDebug() << ui->tableWidget->item(0,i)->text();

    Updatechannels(SelectRowID);

//    int y = ui->tableWidget->rowCount();
//    for (int i = 0; i < y; i++) {
//         qDebug() << "myy " << ui->tableWidget->item(i,0)->text()
//                    <<ui->tableWidget->item(i,1)->text();
//    }

    return;
}

//处理模拟信道
void MainWindow::deal_add_a_ch(QString strv)
{
    qDebug() << "add_a_ch传回的数据为" <<strv;
    QStringList slist = strv.split("#");
    //for (int i = 0; i < slist.size(); i++)
    //    qDebug() << QString("%1").arg(slist.at(i));

    int col = ui->tableWidget->columnCount();
    int row = ui->tableWidget->rowCount();

    CHANNINFO chanelinfo;
    QString str;
    int id;

    if (row == 0) {
       id = 1;
    } else {
       id = ui->tableWidget->item(row-1,0)->text().toInt() + 1;
    }

    str += QString("%1#").arg(id);

    str += QString("%1#").arg(SelectRowID);

    //名字
    //str += QString("Analog Channel%1#").arg(id);
    QString name = QString("%1").arg(slist.at(0));
    str += name + "#";
    chanelinfo.ChannelName = name;

    //类型
    QString type = "A";
    str += type + "#";
    chanelinfo.ChannelType = type;

    //发射频率
    QString tx = QString("%1").arg(slist.at(2));
    str += tx + "#";
    chanelinfo.TXFrequency = tx;

    //接收频率
    QString rx = QString("%1").arg(slist.at(1));
    str += rx + "#";
     chanelinfo.RXFrequency = rx;

    //带宽 1-窄带，2-宽带
    QString Bandwidth;
    if (language == "Chinese")
    {
        if (QString("%1").arg(slist.at(5)) == "宽带")
           Bandwidth = "2";
        else if (QString("%1").arg(slist.at(5)) == "窄带")
            Bandwidth = "1";
    }
    if (language == "English")
    {
        if (QString("%1").arg(slist.at(5)) == "Bandwidth")
           Bandwidth = "2";
        else if (QString("%1").arg(slist.at(5)) == "NarrowBand")
            Bandwidth = "1";
    }


    str += Bandwidth + "#";
    chanelinfo.ColorCode = Bandwidth;

    //功率 1代表高功率，0代表低功率, 默认1(高功率)
    QString power;
    if (language == "Chinese")
    {
        if (QString("%1").arg(slist.at(4)) == "高")
            power = "1";
        else if (QString("%1").arg(slist.at(4)) == "低")
            power = "0";
    }
    if (language == "English")
    {
        if (QString("%1").arg(slist.at(4)) == "High")
            power = "1";
        else if (QString("%1").arg(slist.at(4)) == "Low")
            power = "0";
    }


    str += power + "#";
    chanelinfo.Power = power;

    //接收亚音类型 1-载波,2-模拟亚音,3-正向数字亚音,4-反向数字亚音；默认1-载波
    QString RX_CTCSS_Type;
    if (language == "Chinese")
    {
        if (QString("%1").arg(slist.at(6)) == "载波")
            RX_CTCSS_Type = "1";
        else if (QString("%1").arg(slist.at(6)) == "CTCSS")
            RX_CTCSS_Type = "2";
        else if (QString("%1").arg(slist.at(6)) == "正向CDCSS")
            RX_CTCSS_Type = "3";
        else if (QString("%1").arg(slist.at(6)) == "反向CDCSS")
            RX_CTCSS_Type = "4";
    }
    if (language == "English")
    {
        if (QString("%1").arg(slist.at(6)) == "CarrierWave")
            RX_CTCSS_Type = "1";
        else if (QString("%1").arg(slist.at(6)) == "CTCSS")
            RX_CTCSS_Type = "2";
        else if (QString("%1").arg(slist.at(6)) == "CDCSS")
            RX_CTCSS_Type = "3";
        else if (QString("%1").arg(slist.at(6)) == "CDCSS_Revert")
            RX_CTCSS_Type = "4";
    }
    //qDebug() << "传回来的接收亚音类型" <<RX_CTCSS_Type;

    str += RX_CTCSS_Type + "#";
    chanelinfo.ChannelMode = RX_CTCSS_Type;

    //接收亚音码
    QString RX_CTCSS_Code;
    QString tmp = QString("%1").arg(slist.at(7));
    if (RX_CTCSS_Type == "1") { //如果是载波，数据为0
        RX_CTCSS_Code = "0";
    }
    else
        RX_CTCSS_Code = QString("%1").arg(slist.at(7));
//    if (RX_CTCSS_Type == "2") { //如果是CTCSS,解析 cparallel table
//        QFile file("./ShowInfo/cparallel.txt");
//        if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
//        {
//            QString str = QString("open file[%1]feiled!").arg("./ShowInfo/cparallel.txt.txt");
//            QMessageBox::warning(NULL, "prompt", str, "OK");
//            return;
//        }

//        while(!file.atEnd())
//        {
//            QByteArray line = file.readLine();
//            QString str = QString(line);
//            QStringList tmplist = str.split("#");
//            if ((QString("%1").arg(tmplist.at(0))) == tmp) {
//                RX_CTCSS_Code = QString("%1").arg(tmplist.at(1));
//                RX_CTCSS_Code = RX_CTCSS_Code.simplified();
//                RX_CTCSS_Code.replace(" ", "");
//                break;
//            }
//        }
//        file.close();
//    }

//    if ((RX_CTCSS_Type == "3") || (RX_CTCSS_Type == "4")) { //如果是CDCSS,解析CDCSS
//        QFile file("./ShowInfo/cdcss.txt");
//        if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
//        {
//            QString str = QString("open file[%1]feiled!").arg("./ShowInfo/cdcss.txt");
//            QMessageBox::warning(NULL, "prompt", str, "OK");
//            return;
//        }

//        while(!file.atEnd())
//        {
//            QByteArray line = file.readLine();
//            QString str = QString(line);
//            QStringList tmplist = str.split("#");
//            if ((QString("%1").arg(tmplist.at(0))) == tmp) {
//                RX_CTCSS_Code = QString("%1").arg(tmplist.at(1));
//                RX_CTCSS_Code = RX_CTCSS_Code.simplified();
//                RX_CTCSS_Code.replace(" ", "");
//                break;
//            }
//        }
//        file.close();
//    }

    str += RX_CTCSS_Code + "#";
    chanelinfo.CallType = RX_CTCSS_Code;

    //发射亚音类型
    QString TX_CTCSS_Type;
    if (language == "Chinese")
    {
        if (QString("%1").arg(slist.at(8)) == "载波")
            TX_CTCSS_Type = "1";
        else if (QString("%1").arg(slist.at(8)) == "CTCSS")
            TX_CTCSS_Type = "2";
        else if (QString("%1").arg(slist.at(8)) == "正向CDCSS")
            TX_CTCSS_Type = "3";
        else if (QString("%1").arg(slist.at(8)) == "反向CDCSS")
            TX_CTCSS_Type = "4";
    }
    if (language == "English")
    {
        if (QString("%1").arg(slist.at(8)) == "CarrierWave")
            TX_CTCSS_Type = "1";
        else if (QString("%1").arg(slist.at(8)) == "CTCSS")
            TX_CTCSS_Type = "2";
        else if (QString("%1").arg(slist.at(8)) == "CDCSS")
            TX_CTCSS_Type = "3";
        else if (QString("%1").arg(slist.at(8)) == "CDCSS_Revert")
            TX_CTCSS_Type = "4";
    }

    str += TX_CTCSS_Type + "#";
    chanelinfo.OutputTimeslot = TX_CTCSS_Type;

    //发射亚音码
    QString TX_CTCSS_Code;
    QString ttmp = QString("%1").arg(slist.at(9));
    if (TX_CTCSS_Type == "1") {
        TX_CTCSS_Code = "0";
    }
    else
        TX_CTCSS_Code = QString("%1").arg(slist.at(9));
//    if (TX_CTCSS_Type == "2") { //如果是CTCSS,解析 cparallel table
//        QFile file("./ShowInfo/cparallel.txt");
//        if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
//        {
//            QString str = QString("open file[%1]feiled!").arg("./ShowInfo/cparallel.txt.txt");
//            QMessageBox::warning(NULL, "prompt", str, "OK");
//            return;
//        }

//        while(!file.atEnd())
//        {
//            QByteArray line = file.readLine();
//            QString str = QString(line);
//            QStringList tmplist = str.split("#");
//            if ((QString("%1").arg(tmplist.at(0))) == ttmp) {
//                TX_CTCSS_Code = QString("%1").arg(tmplist.at(1));
//                TX_CTCSS_Code = TX_CTCSS_Code.simplified();
//                TX_CTCSS_Code.replace(" ", "");
//                break;
//            }
//        }
//        file.close();
//    }

//    if ((TX_CTCSS_Type == "3") || (TX_CTCSS_Type == "4")) { //如果是CDCSS,解析CDCSS
//        QFile file("./ShowInfo/cdcss.txt");
//        if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
//        {
//            QString str = QString("open file[%1]feiled!").arg("./ShowInfo/cdcss.txt");
//            QMessageBox::warning(NULL, "prompt", str, "OK");
//            return;
//        }

//        while(!file.atEnd())
//        {
//            QByteArray line = file.readLine();
//            QString str = QString(line);
//            QStringList tmplist = str.split("#");
//            if ((QString("%1").arg(tmplist.at(0))) == ttmp) {
//                TX_CTCSS_Code = QString("%1").arg(tmplist.at(1));
//                TX_CTCSS_Code = TX_CTCSS_Code.simplified();
//                TX_CTCSS_Code.replace(" ", "");
//                break;
//            }
//        }
//        file.close();
//    }

    str += TX_CTCSS_Code + "#";
    chanelinfo.InputTimeslot = TX_CTCSS_Code;

    //音量
    QString volume = QString("%1").arg(slist.at(10));
    str += volume + "#";
    chanelinfo.Volume = volume;

    //静噪
    QString gain = QString("%1").arg(slist.at(11));
    str += gain + "#";
    chanelinfo.MicGain = gain;

    //本地ID
    QString Id = QString("%1").arg(slist.at(3));
    str += Id + "#";
    chanelinfo.Id = Id;

    //联系人号码
    QString num = QString("%1").arg(slist.at(12));
    str += num + "#";
    chanelinfo.num = num;

    //呼叫列表
    QString llist = QString("%1").arg(slist.at(13));
    str += llist + "#";
    chanelinfo.list = llist;

    //密钥
    QString key = QString("%1").arg(slist.at(14));
    str += key + "#";
    chanelinfo.key = key;

    //加密
    QString encrypt;
    if (language == "English")
    {
        if (QString("%1").arg(slist.at(15)) == "Open")
            encrypt = "1";
        else if (QString("%1").arg(slist.at(15)) == "Close")
            encrypt = "0";
    }
    if (language == "Chinese")
    {
        if (QString("%1").arg(slist.at(15)) == "开")
            encrypt = "1";
        else if (QString("%1").arg(slist.at(15)) == "关")
            encrypt = "0";
    }
    str += encrypt + "#";
    chanelinfo.encrypt = encrypt;

    ui->tableWidget->insertRow(row);

    QStringList list = str.split("#");

    QString sId = QString("%1#%2#").arg(SelectRowID).arg(id);
    chanelinfo.AreaID = sId;
    channels.insert(channels.keys().size(),chanelinfo);


    for (int i = 0; i < col; i++) {
        QTableWidgetItem *item = new QTableWidgetItem(list.at(i));
        if (i == 0 || i == 1)
            item->setFlags(item->flags() & (~Qt::ItemIsEditable));
        ui->tableWidget->setItem(row, i, item);
        //ui->tableWidget->item(row,i)->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
    }
    Updatechannels(SelectRowID);
    // qDebug() << "Add A CH " << channels.keys().size();
    return;
}

//处理修改返回来的数据
void MainWindow::deal_moddate(QString str)
{

    qDebug() <<"传回来的数据为" <<str;
    //根据传回来的no和areano修改数据

    QStringList list = str.split("#");

    QString name = QString("%1").arg(list.at(0));
    QString recvfreq = QString("%1").arg(list.at(1));
    QString sendfreq = QString("%1").arg(list.at(2));
    QString id = QString("%1").arg(list.at(3));
    QString power = QString("%1").arg(list.at(4));
    QString colorcode = QString("%1").arg(list.at(5));
    QString mode = QString("%1").arg(list.at(6));
    QString call =QString("%1").arg(list.at(7));
    QString output =QString("%1").arg(list.at(8));
    QString input =QString("%1").arg(list.at(9));
    QString volume =QString("%1").arg(list.at(10));
    QString gain =QString("%1").arg(list.at(11));
    QString no =QString("%1").arg(list.at(12));
    QString areano =QString("%1").arg(list.at(13));
    QString type = QString("%1").arg(list.at(14));
    QString num = QString("%1").arg(list.at(15));
    QString llist = QString("%1").arg(list.at(16));
    QString key = QString("%1").arg(list.at(17));
    QString lencrypt = QString("%1").arg(list.at(18));

    QString tpower,tcolorcode,tmode,tcall,toutput,tinput,tlencrypt;


    //qDebug() << "no = " << no << "areano = " << areano;

    //先修改保存的数据
    QMap<int,CHANNINFO>::iterator i;
    for(i = channels.begin(); i != channels.end();) {
        QString tAreaNo = i.value().AreaID.split("#").at(0);
        QString tNo = i.value().AreaID.split("#").at(1);
        //qDebug() << "tAreaNo = " << tAreaNo << "tNo" << tNo;
        if ((tAreaNo == areano) && (tNo == no)) {
            //找到了要修改的数据
             i.value().ChannelName = name;
             i.value().TXFrequency = sendfreq;
             i.value().RXFrequency = recvfreq;
             i.value().Id = id;

             i.value().num = num;
             i.value().list = llist;
             i.value().key = key;
             if ((lencrypt == "开") || (lencrypt == "Open"))  i.value().encrypt = "1";
             if ((lencrypt == "关") || (lencrypt == "Close"))  i.value().encrypt = "0";

             //如果修改的修道类型时数字信道
            if (i.value().ChannelType == "D") {
                i.value().ColorCode = colorcode;
                if ((power == "高") || (power == "High")) i.value().Power = "1";
                if ((power == "低") || (power == "Low")) i.value().Power = "0";

                if ((mode == "直通模式") || (mode == "Direct-Mode"))  i.value().ChannelMode = "1";
                if ((mode == "真双时隙模式") || (mode == "Double-timeslot"))  i.value().ChannelMode = "2";

                if ((call == "个呼") || (call == "Private")) i.value().CallType = "1";
                if ((call == "组呼") || (call == "Group")) i.value().CallType = "2";
                if ((call == "全呼") || (call == "All")) i.value().CallType = "3";

                if ((output == "时隙1") || (output == "Slot1")) i.value().OutputTimeslot = "1";
                if ((output == "时隙2") || (output == "Slot2")) i.value().OutputTimeslot = "2";

                if ((input == "时隙1") || (input == "Slot1")) i.value().InputTimeslot = "1";
                if ((input == "时隙2") || (input == "Slot2")) i.value().InputTimeslot = "2";

                i.value().Volume = volume;
                i.value().MicGain = gain;
            }

            //如果修改的修道类型时模拟信道
           if (i.value().ChannelType == "A") {
               if ((colorcode == "宽带") || (colorcode == "Bandwidth"))i.value().ColorCode = "2";
               if ((colorcode == "窄带") || (colorcode == "NarrowBand"))i.value().ColorCode = "1";
               if ((power == "高") || (power == "High")) i.value().Power = "1";
               if ((power == "低") || (power == "Low")) i.value().Power = "0";
               if ((mode == "载波") || (mode == "CarrierWave"))  i.value().ChannelMode = "1";
               if ((mode == "CTCSS"))  i.value().ChannelMode = "2";
               if ((mode == "正向CDCSS") || (mode == "CDCSS"))  i.value().ChannelMode = "3";
               if ((mode == "反向CDCSS") || (mode == "CDCSS_Revert"))  i.value().ChannelMode = "4";
//                if (i.value().ChannelMode != "1") {
//                    qDebug() << "myy" << mode << call;
//                    i.value().CallType = index_to_value(i.value().ChannelMode,call);
//                } else
                    i.value().CallType = call;
               if ((output == "载波") || (output == "CarrierWave")) i.value().OutputTimeslot = "1";
               if ((output == "CTCSS")) i.value().OutputTimeslot = "2";
               if ((output == "正向CDCSS") || (output == "CDCSS")) i.value().OutputTimeslot = "3";
               if ((output == "反向CDCSS") || (output == "CDCSS_Revert")) i.value().OutputTimeslot = "4";
//               if (i.value().OutputTimeslot != "1")
//                    i.value().InputTimeslot = index_to_value(i.value().OutputTimeslot,input);
//               else
                   i.value().InputTimeslot = input;
               i.value().Volume = volume;
               i.value().MicGain = gain;
           }

           tcolorcode = i.value().ColorCode;
           tpower = i.value().Power;
           tmode = i.value().ChannelMode;
           tcall = i.value().CallType;
           toutput = i.value().OutputTimeslot;
           tinput = i.value().InputTimeslot;
           tlencrypt = i.value().encrypt;

           break;
        } else
            i++;
    }

    qDebug() << "修改之后的channels大小为" <<channels.keys().size();
    //QMap<int,CHANNINFO>::iterator  i;
    for(i = channels.begin(); i != channels.end();++i) {
        qDebug() << "修改之后的channels数据为"<<i.value().AreaID << i.value().ChannelName << i.value().ChannelType
                 <<i.value().TXFrequency<<i.value().RXFrequency<<i.value().ColorCode<<i.value().Power
                 <<i.value().ChannelMode<<i.value().CallType<<i.value().OutputTimeslot<<i.value().InputTimeslot
                 <<i.value().Volume<<i.value().MicGain<<i.value().Id<<i.value().num<<i.value().key
                <<i.value().encrypt;

    }

    //修改表格上显示的数据

    int col = ui->tableWidget->columnCount();

    //1、得到表格的行数
    int row = ui->tableWidget->rowCount();
    for (int i = 0; i < row; i++) {
         QString tno = ui->tableWidget->item(i,0)->text();
         QString tareano = ui->tableWidget->item(i,1)->text();
        //找到要修改数据的行数
         if ((tno == no) && (tareano == areano)) {
             qDebug() << "找到了要修改的行" <<i;
            QTableWidgetItem *iname = new QTableWidgetItem(name);
            ui->tableWidget->setItem(i, 2, iname);

            //QTableWidgetItem *itype = new QTableWidgetItem(type);
            //ui->tableWidget->setItem(i, 3, itype);

            QTableWidgetItem *isend = new QTableWidgetItem(sendfreq);
            ui->tableWidget->setItem(i, 4, isend);

            QTableWidgetItem *irecv = new QTableWidgetItem(recvfreq);
            ui->tableWidget->setItem(i, 5, irecv);

            QTableWidgetItem *icolor = new QTableWidgetItem(tcolorcode);
            ui->tableWidget->setItem(i, 6, icolor);

            QTableWidgetItem *ipower = new QTableWidgetItem(tpower);
            ui->tableWidget->setItem(i, 7, ipower);

            QTableWidgetItem *imode = new QTableWidgetItem(tmode);
            ui->tableWidget->setItem(i, 8, imode);

            QTableWidgetItem *icall = new QTableWidgetItem(tcall);
            ui->tableWidget->setItem(i, 9, icall);

            QTableWidgetItem *ioutput = new QTableWidgetItem(toutput);
            ui->tableWidget->setItem(i, 10, ioutput);

            QTableWidgetItem *iinput = new QTableWidgetItem(tinput);
            ui->tableWidget->setItem(i, 11, iinput);

            QTableWidgetItem *ivolume = new QTableWidgetItem(volume);
            ui->tableWidget->setItem(i, 12, ivolume);

            QTableWidgetItem *igain = new QTableWidgetItem(gain);
            ui->tableWidget->setItem(i, 13, igain);

            QTableWidgetItem *iid = new QTableWidgetItem(id);
            ui->tableWidget->setItem(i, 14, iid);

            QTableWidgetItem *inum = new QTableWidgetItem(num);
            ui->tableWidget->setItem(i, 15, inum);

            QTableWidgetItem *ilist = new QTableWidgetItem(llist);
            ui->tableWidget->setItem(i, 16, ilist);

            QTableWidgetItem *ikey = new QTableWidgetItem(key);
            ui->tableWidget->setItem(i, 17, ikey);

            QTableWidgetItem *iencrypt = new QTableWidgetItem(tlencrypt);
            ui->tableWidget->setItem(i, 18, iencrypt);


            //qDebug() << "修改之后表格当前行数据为";

            //for (int j = 0; j < col; j++)
            //    qDebug() << ui->tableWidget->item(i,j)->text();

            break;
        }

    }

}




void MainWindow::on_language_clicked()
{
    if (language == "Chinese") {
        //ui->showlog->append("[ 切换为英文显示 ...... ]");
        language = "English";
        //ui->language->setText("中文");
        ui->language->setText("English");


        ui->addarea->setText("Add Zone");
        ui->cleanarea->setText("Clean");
        ui->pushButton_2->setText("Add D CH"); //add d
        ui->pushButton_3->setText("Add A CH"); //add a
        ui->clean->setText("Clean");
        ui->send->setText("Write");
        ui->read->setText("Read");
        ui->choose_file->setText("Choose File ");
        ui->switch_file->setText("Import");
        ui->pushButton->setText("Status");

        //QString str = "No#AreaNo#Channel Name#Channel Type#TX Freq#RF Freq#Color Code/Bandwidth#Power#Channel Mode/RX CTCSS Type#Call Type/RX CTCSS Code#Output Timeslot/TX CTCSS Type#Input Timeslot/TX CTCSS Code#Volume#Mic Gain/Mute#Local ID";
        QString str = "No#AreaNo#Channel Name#Channel Type#TX Freq#RF Freq#Color Code/Bandwidth#Power#Channel Mode/RX CTCSS Type#Call Type/RX CTCSS Code#Output Timeslot/TX CTCSS Type#Input Timeslot/TX CTCSS Code#Volume#Mic Gain/Mute#Local ID#Contact Num#Group List#Encrypt Key#Encrypt";

        headers = str.split("#");
        printStr("切换语言");

        ui->tableWidget->setColumnCount(headers.size()); //设置列数
        ui->tableWidget->setHorizontalHeaderLabels(headers);

        str = "No#Zone Area#Channel List";
        areaheaders = str.split("#");

        ui->areatable->setColumnCount(areaheaders.size()); //设置列数
        ui->areatable->setHorizontalHeaderLabels(areaheaders);

    }
    else if (language == "English") {
        //ui->showlog->append("[ 切换为中文显示 ...... ]");
        language = "Chinese";
        //ui->language->setText("English");
        ui->language->setText("中文");

        ui->addarea->setText("增加信道区域");
        ui->cleanarea->setText("清除区域");
        ui->pushButton_2->setText("添加数字信道"); //add d
        ui->pushButton_3->setText("添加模拟信道"); //add a
        ui->clean->setText("清除信道");
        ui->send->setText("发送文件");
        ui->read->setText("接收文件");
        ui->choose_file->setText("加载文件");
        ui->switch_file->setText("解析");
        ui->pushButton->setText("状态");

        QString str = "序号#区域号#信号名称#信道类型#发射频率#接收频率#色码/带宽#功率#信道模式/接收亚音类型#呼叫类型/接收亚音码#输出时隙/发射亚音类型#输入时隙/发射亚音码#音量#增益/静噪#本地ID#联系人号码#组呼列表#密钥#加密";


        headers = str.split("#");
        qDebug() << "切换语言" << headers.size();


        ui->tableWidget->setColumnCount(headers.size()); //设置列数
        ui->tableWidget->setHorizontalHeaderLabels(headers);

        str = "序号#区域名#信道数";
        areaheaders = str.split("#");

        ui->areatable->setColumnCount(areaheaders.size()); //设置列数
        ui->areatable->setHorizontalHeaderLabels(areaheaders);
    }
    updateFreqDisplay();
}

void MainWindow::printStr(QString str)
{
#if DEBUG
    qDebug() << str;
#endif
}


void MainWindow::on_freq_choose_clicked()
{
    if(freq == V_FREQ){
        freq = U_FREQ;
    }else{
        freq = V_FREQ;
    }
    updateFreqDisplay();
}

void MainWindow::updateFreqDisplay(void)
{
    if(freq == V_FREQ){
        if (language == "Chinese"){
            ui->freq_choose->setText("V段");
        }else{
             ui->freq_choose->setText("V Frequency");
        }
    }else{
        if (language == "Chinese"){
            ui->freq_choose->setText("U段");
        }else{
            ui->freq_choose->setText("U Frequency");
        }
    }
}
